Friday 8 April 2016

the string object in javascript - some important functions

The string object in javascript - some important functions


//Some important functions in the string object in js
var value = 'Some string';
console.log(value.charAt(6));//t
console.log(value.concat(' concatenated with this one.'));
console.log(value.includes(' '));
console.log(value.endsWith('ing'));
console.log(value.endsWith('ing '));/* false - There is a space at the end which is not trimmed by function endsWith() */
console.log(value.indexOf('r'));
console.log(value.indexOf('Z'));//-1 as Z is not found in the string value
console.log(value.lastIndexOf('s'));//starts at the end of the string and goes backwards
console.log(value.slice(5));//string - start at index 5 and return a slice of the original string
console.log(value.slice(5, 8));//str - start at index 5 and returna slice up to but not including index 8
//Give me the final 3 characters starting from the end of the string
console.log(value.slice(-3)); // - ing - negative argument shows starting backwards.

//Splitting a string into an array
var str = "This is a string that we will split into an array on the basis of a space character and has 22 words.";
console.log(str.split(' ').length);//22 because we are splitting using a space and that makes it 22 elements
console.log(str.substr(40, 9));//an array - start at index 40 and return 8 characters.

/* If you want a string that starts at index i and ends at index j but j is not included then use str.substring(i, j) function instead of substr(beginningIndex, numberOfCharactersToReturn) function.
*/
console.log(str.substring(40, 65));//character at 65 is not included.

No comments:

Post a Comment