如何替换javascript中的几个单词 [英] How to replace several words in javascript

查看:43
本文介绍了如何替换javascript中的几个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript中的replace()替换文本中的几个单词,我该怎么做?

I wanna replace several words in a text using replace() in javascript, how can I do that?

例如,如果我想将" 戴夫·钱伯斯,大卫·钱伯斯,威尔·史密斯 "替换为" 成龙 ,无论它们是大写还是小写,我都必须每次都对同一个字符串变量重复执行replace()方法,即

For example, if I wanna replace, 'Dave Chambers, David Chambers, Will Smith' with 'Jackie Chan', no matter if they're in upper-case or lower-case, do I have to keep repeating the replace() method on the same string variable everytime, i.e.

var str = sometext.innerHTML;
str.replace('Dave Chambers', 'Jackie Chan');
str.replace('David Chambers', 'Jackie Chan');
str.replace('Will Smith', 'Jackie Chan');

推荐答案

使用带有交流发电机(|)和不区分大小写的修饰符(/i)的正则表达式:

Use a regular expression with the alternator (|) and case insensitive modifier (/i):

var str = sometext.innerHTML,
    reg = /Dave Chambers|David Chambers|Will Smith/i;

str = str.replace(reg, "Jackie Chan"); 

更短,更复杂的正则表达式可能是:

A shorter, more complex regex could be:

/Dav(?:e|id) Chambers|Will Smith/i;

如果出现的次数超过1,则添加全局修饰符(g)替换所有内容:

And if there may be more than 1 occurrence, add the global modifier (g) to replace all:

/Dav(?:e|id) Chambers|Will Smith/ig;

您可以在此处或通过搜索Google了解更多有关正则表达式的信息.您可以在此处看到工作演示.

You can learn more about regular expressions here, or by searching Google. You can see a working demo here.

这篇关于如何替换javascript中的几个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆