javascript how to separate a string code example
Example 1: javascript split
// bad example https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters/38901550
var arr = foo.split('');
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
Example 2: javascript split string
// Split string into an array of strings
const path = "/usr/home/chucknorris"
let result = path.split("/")
console.log(result)
// result
// ["", "usr", "home", "chucknorris"]
let username = result[3]
console.log(username)
// username
// "chucknorris"
Example 3: javascript slice string from character
var input = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = input.split('~');
var name = fields[0];
var street = fields[1];
Example 4: how to sepaarte text in object javascript
let data = 'Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n';
let target = {};
data.split('\n').forEach((pair) => {
if(pair !== '') {
let splitpair = pair.split(': ');
let key = splitpair[0].charAt(0).toLowerCase() + splitpair[0].slice(1).split(' ').join('');
target[key] = splitpair[1];
}
});
console.dir(target);