Home >Web Front-end >JS Tutorial >Sharing experience in using Replace method in JS_javascript skills

Sharing experience in using Replace method in JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:58:251535browse

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.

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