Javascript - 如何替换子字符串? [英] Javascript - how to replace a sub-string?

查看:78
本文介绍了Javascript - 如何替换子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很简单。我想使用Javascript在客户端用另一个子字符串替换子字符串。

This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.

原始字符串是'原始READ ONLY'

我想用替换'READ ONLY' 'READ WRITE'

I want to replace the 'READ ONLY' with 'READ WRITE'

请问快速回答?可能有一个javascript代码片段...

Any quick answer please? Possibly with a javascript code snippet...

推荐答案

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 字符串可能包含在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.

这篇关于Javascript - 如何替换子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆