且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript - 如何替换子字符串?

更新时间:2023-02-06 17:48:23

String.replace()是基于正则表达式的;如果传入一个字符串作为第一个参数,则由它生成的正则表达式将不包含'g'(全局)标志。如果您想要替换搜索字符串的所有出现(通常是您想要的),此选项是必不可少的。

String.replace() is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the ‘g’ (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).

替代非正则表达式简单全局字符串替换的习惯用语是:

An alternative non-regexp idiom for simple global string replace is:

function string_replace(haystack, find, sub) {
    return haystack.split(find).join(sub);
}

这是 find $ c的首选$ c>字符串可能包含在regexp中具有不需要的特殊含义的字符。

This is preferable where the find string may contain characters that have an unwanted special meaning in regexps.

无论如何,对于问题中的示例,任何一种方法都可以。

Anyhow, either method is fine for the example in the question.