如何在不需要逃避一切的情况下进行全局字符串替换? [英] How do I do global string replace without needing to escape everything?

查看:76
本文介绍了如何在不需要逃避一切的情况下进行全局字符串替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用另一个字符串替换字符串中模式的所有出现。例如,让我们将所有$转换为!:

I want to replace all occurences of a pattern in a string by another string. For example, lets convert all "$" to "!":

"$$$" -> "!!!"

普通字符串.replace仅替换第一场比赛:

Plain string.replace replaces only the first match:

"$$$".replace("$", "!"); // gives "$!!"

和正则表达式迫使我逃到特殊字符

and regexes force me to escape to special chars

"$$$".replace(/\$/g, "!"); // Pattern is now full of backslashes!

是否可以在不必手动转义特殊字符的情况下进行全局替换?我有一堆模式是我的代码的一部分,我认为如果必须手动逃避所有这些模式,可读性会受到影响。

Is it possible to do the global replacement without having to manually escape the special characters? I have a bunch of patterns is a part of my code and I think readability would suffer if had to escape all of them by hand.

我期待要么是直接做我想要的技巧,要么至少是一种将字符串转换成可用于新的RegExp

I'm expecting either a trick that directly does what I want or at least a way to convert a string to an excaped form useable by new RegExp

推荐答案

Javascript中没有标准的regexp转义函数。

There is no standard regexp escape function in Javascript.

你可以编写自己的( source )或从您的图书馆获取( dojo示例

You can write your own (source) or get it from your library (dojo example)

function escape(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
};






这允许我们在以下位置创建自定义正则表达式对象运行时


This allows us to create the custom regex object at runtime

function replace_all(string, pattern, replacement){
    return string.replace( new RegExp(escape(pattern), "g"), replacement);
}

这篇关于如何在不需要逃避一切的情况下进行全局字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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