admin管理员组文章数量:1410697
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.
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.
Share edited Nov 2, 2014 at 1:41 falsetru 370k67 gold badges765 silver badges658 bronze badges asked Sep 13, 2013 at 16:47 Mirza DelicMirza Delic 4,35912 gold badges59 silver badges88 bronze badges 01 Answer
Reset to default 7Use RegExp
to dynamically generate regular expression:
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = new RegExp('[' + escapeRegExp(separator) + '\\s]', 'g');
escapeRegExp
es from Regular Expressions - JavaScript | MDN.
NOTE: You have to escape \
, and separator
.
本文标签: javascript regex replace variableStack Overflow
版权声明:本文标题:javascript regex replace variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744926922a2632656.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论