最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery replace variable in all text syntax regex - Stack Overflow

programmeradmin5浏览0评论

This does not work because of the variable rep. What is the correct syntax please?

var bigtext = 'testing test test test';
var rep = 'test'; 
bigtext = bigtext.replace(/rep/g, "MOO!");

I know the problem is with the regex part in the replace...but what is the correct way to write it?

This does not work because of the variable rep. What is the correct syntax please?

var bigtext = 'testing test test test';
var rep = 'test'; 
bigtext = bigtext.replace(/rep/g, "MOO!");

I know the problem is with the regex part in the replace...but what is the correct way to write it?

Share Improve this question edited Aug 14, 2012 at 14:19 olly_uk 11.9k3 gold badges41 silver badges45 bronze badges asked Aug 14, 2012 at 14:15 David19801David19801 11.4k26 gold badges86 silver badges127 bronze badges 3
  • possible duplicate of Using a string variable as regular expression and Pass a variable into regex with string replace. – Felix Kling Commented Aug 14, 2012 at 14:18
  • And what has jQuery got to do with basic regular expressions? – epascarello Commented Aug 14, 2012 at 14:18
  • @David: epascarello's point was that this has nothing to do with jQuery. Regular expressions are a feature of the language itself. – Felix Kling Commented Aug 14, 2012 at 14:21
Add a ment  | 

1 Answer 1

Reset to default 7

You need to build a regex using the RegExp constructor:

var bigtext = 'testing test test test';
var rep = 'test'; 
var regex = new RegExp(rep, 'g');
bigtext = bigtext.replace(regex, "MOO!");

Documentation for this constructor can be seen on the MDN page. Note that you probably should make sure that any special characters in regular expressions (e.g. [) are escaped.

发布评论

评论列表(0)

  1. 暂无评论