简体   繁体   English

多次替换字符

[英]Replace character more than once

Here is a fiddle http://jsfiddle.net/aLr2yx8d/ 这是一个小提琴http://jsfiddle.net/aLr2yx8d/

$('#inputButton').click(function() {    

    var value = $('#input').val(); 
    var re = /\./g;
    var output = $('#output');

    var text = output.text().replace(re, value);
    output.html(text); 

});

Now I can only update it once. 现在,我只能更新一次。 I want to have the possibility to update it more than once. 我想有可能不止一次更新它。 The first time it will replace the dot (.) and the second time it has to replace the first value I gave. 第一次它将替换点(。),第二次必须替换我给的第一个值。

You can use a variable to hold the variable RegularExpression you wish to change. 您可以使用变量保存要更改的变量RegularExpression。 For example: 例如:

var regExVal= /\./g;
$('#inputButton').click(function() {    

    var value = $('#input').val(); 
    var re = regExVal;
    regExVal= new RegExp(value, "g"); <-- this is how you set the new value
    var output = $('#output');

    var text = output.text().replace(re, value);
    output.html(text); 

});

Here's the JsFiddle 这是JsFiddle

Edit: 编辑:

As I mentioned in the comment, you would need to escape certain characters for use as characters in the Regular Expression instead of operators. 正如我在评论中提到的那样,您需要转义某些字符以用作正则表达式中的字符而不是运算符。 I found a good answer to that in another question . 在另一个问题中 ,我找到了一个很好的答案。 Include it in your script: 将其包括在脚本中:

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Then, before using the value , you do something like: 然后,在使用value之前,您需要执行以下操作:

value = escapeRegExp(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM