
String Data Type: In this chapter we will look into inbuilt methods for string data type.
- lowercase,
- uppercase,
- search,
- replace,
- match,
- trim
- indexOf
- substring
- charAt
1 toLowerCase(): The method converts given string into lowercase.
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toLowerCase());
2 toUpperCase(): The method converts given string into uppercase.
const sentence = 'The quick brown fox jumps over the lazy dog.'; console.log(sentence.toUpperCase());
3 search(): The method executes a search for a match between a regular expression and given string object.
const para = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const regex = /[^\w\s]/g; console.log(para.search(regex));
console.log(para[para.search(regex)]);
4 replace(): The method search and replaces the word from given string.
const para = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi; console.log(para.replace(regex, 'ferret'));
console.log(para.replace('dog', 'monkey'));
5 match():
The
method retrieves the result of matching a string against a regular expression.
const para = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g; const found = para.match(regex);
6 trim(): The method removes whitespace from both ends of a string.
const greeting = ' Hello world! '; console.log(greeting); // expected output: " Hello world! ";
7 indexOf(): The method returns the index within the given string of the first occurrence of the specified value, starting the search at from Index. returns -1 if the value is not found.
const para = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; const searchTerm = 'dog'; const indexOfFirst = para.indexOf(searchTerm); console.log('The index of the first "' + searchTerm + '" from the beginning is ' + indexOfFirst); //expected output: "The index of the first "dog" from the beginning is 40" console.log('The index of the 2nd "' + searchTerm + '" is ' + para.indexOf(searchTerm, (indexOfFirst + 1))); // expected output: "The index of the 2nd "dog" is 52"
8 substring(): The method returns the part of the string between the start and end indexes, or to the end of the string.
const str = 'Mozilla';
console.log(str.substring(1, 3));
// expected output: "oz"
9 charAt: The String object’s charAt() method returns character at specified index form string.
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log('The character at index ' + index + ' is ' +
sentence.charAt(index));
// expected output: "The character at index 4 is q"