jQuery:如何替换某些字符之间的所有字符?
我已经找到了解决这个问题的一般方法,但是只能找到人们特定问题的答案.
I have searched for a general solution to this but only find answers to peoples specific questions.
基本上,我想知道如何通常使用.replace()替换字符串中任何种类的字符之间的项目,例如:
Basically, I want to know how to generally use .replace() to replace items in between any kind of characters in a string, eg:
替换介于abc和xyz之间的所有文本,例如:abc text to be replaced xyz
Replace all text in between and inclusive of abc and xyz eg: abc text to be replaced xyz
或替换介于两者之间的所有文本,包括<img and />
,例如:<img src="image.jpg" />
or replace all text in between and inclusive of <img and />
eg: <img src="image.jpg" />
有人能帮我这个忙吗?或为我指点一下?
Can anyone help me out or point me in the direction of a good tute on this?
谢谢!让我知道是否需要进一步说明.
Thanks! Let me know if I need to clarify more.
您要查找的内容称为正则表达式.有关更多信息,您可以访问以下网站: http://www.regular-expressions.info/
What you are looking for are called regular expressions. For more information, you can visit a site like: http://www.regular-expressions.info/
请注意,正则表达式并非特定于JavaScript.
Note that regular expressions are not specific to JavaScript.
对于您的具体示例:
string.replace(/abc.+xyz/,"abc"+newString+"xyz");
.表示任何字符,而+表示一个或多个事件.
. means any character, and + means one or more occurences.
如果您要进行多个替换,请尝试:
If you have more than one replacement to do, try:
string.replace(/abc.+?xyz/g,"abc"+newString+"xyz");
g代表将军,而?是惰性的量词,表示它将在字符串中xyz的下一次出现时停止.
g stands for general, and ? is the lazy quantifier, meaning that it will stop at the next occurence of xyz in the string.