Ant*_*ony 25 javascript string lodash
如何用另一个字符串替换字符串中每个字符串模式的出现?
var text = "azertyazerty";
_.replace(text,"az","qu")
Run Code Online (Sandbox Code Playgroud)
返回 quertyazerty
小智 33
你也可以
var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");
Run Code Online (Sandbox Code Playgroud)
Ant*_*ony 31
你必须使用lodash提供的全局选项RegExp.
所以只需使用
var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
Run Code Online (Sandbox Code Playgroud)
回来 quertyquerty
Sim*_*son 11
我喜欢lodash,但这可能是没有它的少数事情之一.
var str = str.split(searchStr).join(replaceStr)
Run Code Online (Sandbox Code Playgroud)
作为具有一些错误检查的实用功能:
var replaceAll = function (str, search, replacement) {
var newStr = ''
if (_.isString(str)) { // maybe add a lodash test? Will not handle numbers now.
newStr = str.split(search).join(replacement)
}
return newStr
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,如果你确实想要使用lodash,那么要实际替换文本,将结果赋给变量.
var text = 'find me find me find me'
text = _.replace(text,new RegExp('find','g'),'replace')
Run Code Online (Sandbox Code Playgroud)
Vanilla JS 完全有能力在没有 lodash 帮助的情况下做你需要的事情。
const text = "azertyazerty"
text.replace(new RegExp("az", "g"), "qu")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37160 次 |
| 最近记录: |