split method in js code example

Example 1: string split javascript

var myString = "An,array,in,a,string,separated,by,a,comma";
var myArray = myString.split(",");
/* 
*
*  myArray :
*  ['An', 'array', 'in', 'a', 'string', 'separated', 'by', 'a', 'comma']
*
*/

Example 2: javascript split

// bad example https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters/38901550#38901550

var arr = foo.split(''); 
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

Example 3: split array javascript

// Returns new array from exising one
arr.slice(start, end);

Example 4: js split string

var myString = "Hello World!";

// splitWords is an array
// [Hello,World!]
var splitWords = myString.split(" ");

// e.g. you can use it as an index or remove a specific word:
var hello = splitWords[splitWords.indexOf("Hello")];

Example 5: 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)

Example 6: javascript split regex

str.split(separator/*, limit*/)

/*Syntax explanation -----------------------------
Returns an array of strings seperated at every 
point where the 'separator' (string or regex) occurs. 
The 'limit' is an optional non-sub-zero integer. 
If provided, the string will split every time the 
separator occurs until the array 'limit' has been reached.
*/

//Example -----------------------------------------
const str = 'I need some help with my code bro.';

const words = str.split(' ');
console.log(words[6]);
//Output: "code"

const chars = str.split('');
console.log(chars[9]);
//Output: "m"

const limitedChars = str.split('',10);
console.log(limitedChars);
//Output: Array ["I", " ", "n", "e", "e", "d", " ", "s", "o", "m"]

const strCopy = str.split();
console.log(strCopy);
//Output: Array ["I need some help with my code bro."]

Tags:

Java Example