Home >Web Front-end >JS Tutorial >How to replace elements in JavaScript strings

How to replace elements in JavaScript strings

coldplay.xixi
coldplay.xixiOriginal
2021-03-31 17:03:474402browse

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.

How to replace elements in JavaScript strings

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn