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

Sharing experience in using Replace method in JS_javascript skills

WBOY
Release: 2016-05-16 15:58:25
Original
1496 people have browsed it

I recently checked a bug. The reason is caused by the Replace method in JS. When there is a place in a string that needs to be replaced, the Replace method in JS is generally used. If the first parameter of the Replace method is passed string, only the first character will be replaced. The code is as follows:

Copy code The code is as follows:

var str = "0CEA65D5-DB8E-4876-A6F8-C88AC7F0E185,E846C244-8A19-4374-879B-0B1DC08D1747,6CB3EBA4-1E22-4E4D-8800-AE31130B6F5D";
alert(str.replace(",","','"));

The above code is intended to replace the commas of GUIDs separated by commas with ',', but the actual result is only the first comma is replaced.

To solve this problem, just use the regular method for the first parameter of replace. The code is as follows:

Copy code The code is as follows:

var reg = new RegExp(",","g");
var str = "0CEA65D5-DB8E-4876-A6F8-C88AC7F0E185,E846C244-8A19-4374-879B-0B1DC08D1747,6CB3EBA4-1E22-4E4D-8800-AE31130B6F5D";
alert(str.replace(reg,"','"));

The results are as follows:

The above is the entire content of the text. I hope it will be helpful to everyone learning javascript.

Related labels:
js
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