MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript String Find and Replace Functions

To 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.


var 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.


var 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.


var string = "Hello, World!";
console.log( string.includes("Hello") ); // true
console.log( string.includes("foo") ); // false
replace( regexp|substring, replacement|replaceFunction )

replace() will return a string that has all occurrences of substrings matching the RegExp regexp or stringsubstring with a string replacement or the returned value of replaceFunction.

Note that this does not modify the string in place, but returns the string with replacements.


var string = "Hello, World!";
string = string.replace( "Hello", "Bye" );
console.log( string );
string = string.replace( /W.{3}d/g, "Universe" );
console.log( string ); 

Output

"Bye,world"
"Bye, Universe!"

replaceFunction can be used for conditional replacements for regular expression objects (i.e., with use with regexp).



Conclusion

In this page (written and validated by ) you learned about Javascript String Find and Replace Functions . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript String to Upper Case.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.