spli js code example

Example 1: javascript split by comma

<script>
var names = 'Harry,John,Clark,Peter,Rohn,Alice';
var nameArr = names.split(',');
console.log(nameArr);
 
// Accessing individual values
alert(nameArr[0]); // Outputs: Harry
alert(nameArr[1]); // Outputs: John
alert(nameArr[nameArr.length - 1]); // Outputs: Alice
 
var str = 'Hello World!';
var chars = str.split('');
console.log();
 
// Accessing individual values
alert(chars[0]); // Outputs: H
alert(chars[1]); // Outputs: e
alert(chars[chars.length - 1]); // Outputs: !
</script>

Example 2: string to array javascript

const str = 'Hello!';

console.log(Array.from(str)); //  ["H", "e", "l", "l", "o", "!"]

Example 3: split() javascript

let countWords = function(sentence){
    return sentence.split(' ').length;
}

console.log(countWords('Type any sentence here'));

//result will be '4'(for words in the sentence)