简体   繁体   中英

Javascript replace all occurrences

I need to convert a sub-string of a string with a character in javascript.

I used following code to do that

av_text_to_display = av_text_to_display.replace("a*^!", "'");

but it can only replace first occurrence. I used following code for all occurrences

av_text_to_display = av_text_to_display.replace("a*^!", "'", "g");

but it is not a standard way. What is the standard way to do that?

您正在使用字符串而不是 RegExp 进行搜索,它可能应该是:

av_text_to_display.replace(/a*\^!/g, "'");

If you're trying to replace that literal string, and not a regex matching that string, use an escaped regex:

av_text_to_display = av_text_to_display.replace(/a\*\^!/g, "'");

 var av_text_to_display = "here: a*^!, there: a*^! and also here, twice: a*^!a*^!"; av_text_to_display = av_text_to_display.replace(/a\\*\\^!/g, "'"); console.log(av_text_to_display);

If you don't want to use regex you can use the both split and join functions to do this :

your_string.split("a").join("'");

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM