Home >Web Front-end >JS Tutorial >How to replace elements in JavaScript strings
Methods for JavaScript string replacement elements: 1. Use [string.replace()]; 2. Use [indexof (“a”)] to return the position of a; 3. Use [split()] and 【join()】Two functions.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Methods for JavaScript string replacement elements:
First method: The first thing that comes to mind when seeing replacement is string.replace ()
var str="hello world"; var newStr=str.replace("hello",'goodbay'); console.log(newStr);// goodbay world
But only replace the first var str = "aaaaabbbbb" and replace a with A
var str='aaaaaaaaaaaaaabbbbbbbbbbbbbb';var newStr=str.replace("a",'A'); console.log(newStr);// Aaaaaaaaaaaaaabbbbbbbbbbbbbb
Use replace and regular expressions to solve the above problem Problem (use regular expressions to match qualified values, and then replace)
console.log(str.replace(/a/g, "b")); //bbbbbbbbbbbbbbbbbbbbbbbbbbbb
The second method: is the most conventional idea to traverse, indexof ("a") returns a If the position does not return -1, as long as a exists, it will loop and replace a until all a's are replaced
while(str.indexOf('a')>=0) { str= str.replace('a','b'); console.log(str);//bbbbbbbbbbbbbbbbbbbbbbbbbbbb }
The third method: use the split() and join() functions
str.split("a").join("b"); console.log(str);//bbbbbbbbbbbbbbbbbbbbbbbbbbbb
First use split to cut the string into ["", "", "", "", "", "", "", "", "", "", " ", "", "", "", "bbbbbbbbbbbbbb"] Then use join to convert all the elements in the array into a string, and use b as the interval bbbbbbbbbbbbbbbbbbbbbbbbb
Related free learning Recommended: javascript video tutorial
The above is the detailed content of How to replace elements in JavaScript strings. For more information, please follow other related articles on the PHP Chinese website!