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

Using JavaScript's replace() method with global switch on a variable - Stack Overflow

programmeradmin4浏览0评论

I can't any example of this after being unable to puzzle out how it would work on my own.

All I want to do is take a string which has been assigned to a value, and use that as the replace match string for all matches.

var replacement = 'i';
var text = 'tieiam';

text = text.replace(replacement, '');  // 'teiam'

text = text.replace(/tieiam/g, ''); // 'team'

How do I use them together??

I can't any example of this after being unable to puzzle out how it would work on my own.

All I want to do is take a string which has been assigned to a value, and use that as the replace match string for all matches.

var replacement = 'i';
var text = 'tieiam';

text = text.replace(replacement, '');  // 'teiam'

text = text.replace(/tieiam/g, ''); // 'team'

How do I use them together??

Share Improve this question asked Jun 26, 2009 at 13:32 Trevor BrambleTrevor Bramble 8,8136 gold badges32 silver badges29 bronze badges 1
  • possible duplicate of How do you pass a variable to a Regular Expression JavaScript? – fxp Commented Nov 6, 2013 at 7:46
Add a comment  | 

1 Answer 1

Reset to default 21

What you want is to use the RegExp object:

text = text.replace(new RegExp(replacement, 'g'), '');

Simple example of it in action.

发布评论

评论列表(0)

  1. 暂无评论