JC *_*bbs 1250 javascript regex
我想在JavaScript中创建一个String.replaceAll()方法,我认为使用RegEx将是最简洁的方法.但是,我无法弄清楚如何将变量传递给RegEx.我已经可以做到这一点,它将用"A"替换所有"B"的实例.
"ABABAB".replace(/B/g, "A");
Run Code Online (Sandbox Code Playgroud)
但我想做这样的事情:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
Run Code Online (Sandbox Code Playgroud)
但显然这只会替换文本"replaceThis"...所以如何将此变量传递给我的RegEx字符串?
Eri*_*lin 1709
/regex/g
您可以构造一个新的RegExp对象,而不是使用语法:
var replace = "regex";
var re = new RegExp(replace,"g");
Run Code Online (Sandbox Code Playgroud)
您可以通过这种方式动态创建正则表达式对象.然后你会做:
"mystring".replace(re, "newstring");
Run Code Online (Sandbox Code Playgroud)
Gra*_*tes 200
正如Eric Wendelin所说,你可以这样做:
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
Run Code Online (Sandbox Code Playgroud)
这产生了"regex matching ."
.但是,如果str1是,它将失败"."
.你期望得到的结果"pattern matching regex"
,取代期间"regex"
,但结果是......
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
Run Code Online (Sandbox Code Playgroud)
这是因为,尽管"."
是一个String,但在RegExp构造函数中,它仍然被解释为正则表达式,这意味着任何非换行符,表示字符串中的每个字符.为此,以下功能可能有用:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
Run Code Online (Sandbox Code Playgroud)
屈服"pattern matching regex"
.
bob*_*nce 110
"ABABAB".replace(/B/g, "A");
一如既往:除非必须,否则不要使用正则表达式.对于简单的字符串替换,成语是:
'ABABAB'.split('B').join('A')
Run Code Online (Sandbox Code Playgroud)
那么你不必担心Gracenotes答案中提到的引用问题.
小智 32
对于任何希望使用匹配方法使用变量的人来说,这对我有用
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Run Code Online (Sandbox Code Playgroud)
Jer*_*ten 30
这个:
var txt=new RegExp(pattern,attributes);
Run Code Online (Sandbox Code Playgroud)
相当于:
var txt=/pattern/attributes;
Run Code Online (Sandbox Code Playgroud)
请参见http://www.w3schools.com/jsref/jsref_obj_regexp.asp.
JBa*_*lin 26
如果你想获得ALL occurrence(g
),不区分大小写(i
),并使用边界,使它不是另一个单词(\\b
)中的单词:
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
Run Code Online (Sandbox Code Playgroud)
例:
let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
Run Code Online (Sandbox Code Playgroud)
tva*_*son 18
this.replace( new RegExp( replaceThis, 'g' ), withThis );
Run Code Online (Sandbox Code Playgroud)
Sal*_*n A 13
您想要动态构建正则表达式,为此,正确的解决方案是使用new RegExp(string)
构造函数.为了让构造函数按字面意思处理特殊字符,您必须将它们转义.在jQuery UI自动完成小部件中有一个内置函数,名为$.ui.autocomplete.escapeRegex
:
[...]您可以使用内置
$.ui.autocomplete.escapeRegex
功能.它将采用单个字符串参数并转义所有正则表达式字符,使结果安全传递给new RegExp()
.
如果您使用的是jQuery UI,则可以使用该函数,或者从源代码复制其定义:
function escapeRegex( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
// escapeRegex("[z-a]") -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result -> "[a-z][a-z][a-z]"
Run Code Online (Sandbox Code Playgroud)
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(replaceThis,"g");
return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");
Run Code Online (Sandbox Code Playgroud)
使用此工具进行测试
为了满足我将变量/别名/函数插入正则表达式的需要,这就是我想出的:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
Run Code Online (Sandbox Code Playgroud)
其中“oldre”是我要插入变量的原始正则表达式,“xx”是该变量/别名/函数的占位符,“yy”是实际的变量名称、别名或函数。
String.prototype.replaceAll = function(a, b) {
return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}
Run Code Online (Sandbox Code Playgroud)
测试它像:
var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'
console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
Run Code Online (Sandbox Code Playgroud)
以及Steven Penny 的答案的 CoffeeScript 版本,因为这是 #2 Google 结果......即使 CoffeeScript 只是删除了很多字符的 JavaScript......;)
baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food
Run Code Online (Sandbox Code Playgroud)
在我的特殊情况下:
robot.name = hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
console.log "True!"
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以将字符串用作正则表达式。不要忘记使用new RegExp。
例子:
var yourFunction = new RegExp(
'^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
682371 次 |
最近记录: |