Home > Web Front-end > JS Tutorial > body text

How to replace elements in JavaScript strings

coldplay.xixi
Release: 2023-01-03 09:32:06
Original
4362 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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 }
Copy after login

The third method: use the split() and join() functions

str.split("a").join("b");
console.log(str);//bbbbbbbbbbbbbbbbbbbbbbbbbbbb
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!