我想在JavaScript中创建String.replaceAll()
方法,并且我认为使用正则表达式是最简洁的方法。 但是,我不知道如何将变量传递给正则表达式。 我已经可以这样做了,它将用"A"
替换"B"
所有实例。
"ABABAB".replace(/B/g, "A");
但是我想做这样的事情:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
但是显然,这只会替换文本"replaceThis"
...所以如何将这个变量传递给我的正则表达式字符串?
#1楼
对于希望将变量与match方法一起使用的任何人,这对我来说都很有效
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
#2楼
这是另一个replaceAll实现:
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if ( stringToFind == stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
#3楼
为了满足我在正则表达式中插入变量/别名/函数的需要,这是我想到的:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
其中“ oldre”是我要插入变量的原始正则表达式,“ xx”是该变量/别名/函数的占位符,“ yy”是实际的变量名,别名或函数。
#4楼
如果$ 1不起作用,则可以使用此功能
var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");
#5楼
您总是可以重复使用indexOf
:
String.prototype.replaceAll = function(substring, replacement) {
var result = '';
var lastIndex = 0;
while(true) {
var index = this.indexOf(substring, lastIndex);
if(index === -1) break;
result += this.substring(lastIndex, index) + replacement;
lastIndex = index + substring.length;
}
return result + this.substring(lastIndex);
};
当替换包含匹配项时,这不会陷入无限循环。
#6楼
String.prototype.replaceAll = function(a, b) {
return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}
像这样测试:
var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'
console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
#7楼
您想动态地构建正则表达式,为此,正确的解决方案是使用new RegExp(string)
构造函数。 为了使构造函数按字面意义处理特殊字符,必须对它们进行转义。 jQuery UI自动完成小部件中有一个内置函数,称为$.ui.autocomplete.escapeRegex
:
您可以利用内置的
$.ui.autocomplete.escapeRegex
函数。 它只需要一个字符串参数,并转义所有正则表达式字符,因此可以安全地将结果传递给new RegExp()
。
如果您使用的是jQuery UI,则可以使用该函数,也可以从源代码复制其定义:
function escapeRegex( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
并像这样使用它:
"[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]"
#8楼
还有史蒂文·潘尼(Steven Penny)答案的coffeescript版本,因为这是Google搜索结果的#2。...即使咖啡只是JavaScript,并且删除了很多字符...;)
baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food
在我的情况下
robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
console.log "True!"
#9楼
您的解决方案在这里:
我实现的一个方法是从一个文本字段中获取值,该文本字段是您要替换的值,另一个是“替换为”文本字段,从文本字段中获取值的变量并将变量设置为RegExp功能进一步取代。 就我而言,我使用的是Jquery,您也可以仅通过JavaScript来实现。
JavaScript代码:
var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.
var sRegExInput = new RegExp(replace, "g");
$("body").children().each(function() {
$(this).html($(this).html().replace(sRegExInput,replace_with));
});
该代码位于按钮的Onclick事件上,您可以将其放入函数中进行调用。
因此,现在您可以在replace函数中传递变量。
#10楼
您可以构造一个新的RegExp对象, /regex/g
使用/regex/g
语法:
var replace = "regex";
var re = new RegExp(replace,"g");
您可以通过这种方式动态创建正则表达式对象。 然后,您将执行以下操作:
"mystring".replace(re, "newstring");
#11楼
this.replace( new RegExp( replaceThis, 'g' ), withThis );
#12楼
这个:
var txt=new RegExp(pattern,attributes);
等效于此:
var txt=/pattern/attributes;
参见http://www.w3schools.com/jsref/jsref_obj_regexp.asp 。
#13楼
正如Eric Wendelin所述,您可以执行以下操作:
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
这产生"regex matching ."
。 但是,如果str1为"."
,它将失败"."
。 您可能希望结果是"pattern matching regex"
,用"regex"
代替句点,但结果是...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
这是因为,尽管"."
是一个字符串,在RegExp构造函数中,它仍被解释为正则表达式,表示任何非换行符,表示字符串中的每个字符。 为此,以下功能可能有用:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
然后,您可以执行以下操作:
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
产生"pattern matching regex"
。
#14楼
尽管您可以制作动态创建的RegExp(根据对此问题的其他回答),但我会在类似的帖子中回应我的评论: String.replace()的功能形式非常有用,并且在许多情况下减少了对动态创建的RegExp对象。 (这很麻烦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜杠/ [AZ] + / regexp文字格式)
#15楼
"ABABAB".replace(/B/g, "A");
一如既往:除非必须,否则不要使用正则表达式。 对于简单的字符串替换,惯用法是:
'ABABAB'.split('B').join('A')
这样,您就不必担心Gracenotes答案中提到的报价问题。
#16楼
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(replaceThis,"g");
return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");
用这个工具测试
#17楼
如果要获取所有出现的字符( g
),请不要区分大小写( i
),并使用边界以使它不是另一个单词( \\\\b
)中的一个单词:
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
例:
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.
#18楼
这些答案对我来说都不是很清楚。 我最终在http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/找到了很好的解释
简单的答案是:
var search_term = new RegExp(search_term, "g");
text = text.replace(search_term, replace_term);
例如:
$("button").click(function() { Find_and_replace("Lorem", "Chocolate"); Find_and_replace("ipsum", "ice-cream"); }); function Find_and_replace(search_term, replace_term) { text = $("textbox").html(); var search_term = new RegExp(search_term, "g"); text = text.replace(search_term, replace_term); $("textbox").html(text); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textbox> Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum </textbox> <button>Click me</button>
#19楼
对于没有正则表达式的多次替换,我进行了以下操作:
let str = "I am a cat man. I like cats";
let find = "cat";
let replace = "dog";
// Count how many occurrences there are of the string to find
// inside the str to be examined.
let findCount = str.split(find).length - 1;
let loopCount = 0;
while (loopCount < findCount)
{
str = str.replace(find, replace);
loopCount = loopCount + 1;
}
console.log(str);
// I am a dog man. I like dogs