js slice string code example
Example 1: js substring
// the substring method returns a string out of another string
const str = 'Mozilla';
console.log(str.substring(1, 3));
// expected output: "oz"
console.log(str.substring(2));
// expected output: "zilla"
Example 2: js string slicing
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
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: string splice
newStr = str.split(''); // or newStr = [...str];
newStr.splice(2,5);
newStr = newStr.join('');
Example 5: slice string js
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31)); // expected output: "the lazy dog."
console.log(str.slice(4, 19)); // expected output: "quick brown fox"
console.log(str.slice(-4)); // expected output: "dog."
console.log(str.slice(-9, -5)); // expected output: "lazy"
// source : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
Example 6: slice string javascript if has @
let email = '[email protected]'
let localPart = email.slice(0,email.indexOf('@'));