0

How can i replace character with regex, but from variable. Example:

var separator = '-';
text = text.replace(/[-\s]+/g, separator);

this will replace - trailing character with separator, which i the same in this case.

So, i need to set this - character from variable separator:

var separator = '-';
var regex = '/['+separator+'\s]+/g';
text = text.replace(regex, separator);

How can i do this? Thanks.

4

1 回答 1

7

用于RegExp动态生成正则表达式:

function escapeRegExp(string){
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = new RegExp('[' + escapeRegExp(separator) + '\\s]', 'g');

escapeRegExp来自正则表达式 - JavaScript | MDN

注意:你必须逃脱\,并且separator

于 2013-09-13T16:49:08.293 回答