Find and replace
suggest changeTo search for a string inside a string, there are several functions:
indexOf( searchString ) and lastIndexOf( searchString )
indexOf() will return the index of the first occurrence of searchString in the string. If searchString is not found, then -1 is returned.
const string = "Hello, World!";
console.log( string.indexOf("o") ); // 4
console.log( string.indexOf("foo") ); // -1
Similarly, lastIndexOf() will return the index of the last occurrence of searchstring or -1 if not found.
const string = "Hello, World!";
console.log( string.lastIndexOf("o") ); // 8
console.log( string.lastIndexOf("foo") ); // -1
includes( searchString, start )
includes() will return a boolean that tells whether searchString exists in the string, starting from index start (defaults to 0). This is better than indexOf() if you simply need to test for existence of a substring.
const string = "Hello, World!";
console.log( string.includes("Hello") ); // true
console.log( string.includes("foo") ); // false
replace( regexp|substring, replacement|replaceFunction )
replace() returns a new string. A string search, or a regular expression without the g flag, replaces only the first match. A regular expression with g replaces every match. The replacement is a string or the return value of replaceFunction. The original string is unchanged.
let string = "Hello, World!";
string = string.replace( "Hello", "Bye" );
console.log( string ); // "Bye, World!"
string = string.replace( /W.{3}d/g, "Universe" );
console.log( string ); // "Bye, Universe!"
A function replacement receives, in order:
| Parameter | Meaning |
|---|---|
| match | the substring that matches the entire regular expression |
| g1, g2, g3, … | the matching groups in the regular expression |
| offset | the offset of the match in the entire string |
| string | the entire string |
You can omit parameters you do not use. If the pattern has named groups, a groups object is inserted before offset.
let string = "heLlo, woRlD!";
string = string.replace( /([a-zA-Z])([a-zA-Z]+)/g, function(match, g1, g2) {
return g1.toUpperCase() + g2.toLowerCase();
});
console.log( string ); // "Hello, World!"