如何替换两个符号之间出现的所有字符串? [英] how to replace all occurrence of string between two symbols?
问题描述
我正在 Javascript 上使用 RegEx,这就是我坚持的地方.
I'm working with RegEx on Javascript and here is where I stuck.
我有一个简单的字符串
<html><body><span style=3D"font-family:Verdana; color:#000; font-size:10pt;=
"><div><font face=3D"verdana, geneva" size=3D"2">http://72.55.146.142:8880/=
order003.png.zip,120</body></html>
我需要做的就是编写可以用<"替换所有字符串的javascript和>"符号.
all i need to do is write javascript which can replace all strings in with "<" and ">" symbol.
我写了这样的东西-
var strReplaceAll = Body;
var intIndexOfMatch = strReplaceAll.indexOf( "<" );
while (intIndexOfMatch != -1){
strReplaceAll = strReplaceAll.replace(/<.*>/,'')
intIndexOfMatch = strReplaceAll.indexOf( "<" );
}
但问题是如果正文包含 -
but the problem is if body contains -
test<abc>test2<adg>
它会给我 -
test
仅或如果正文包含喜欢 -
only or if body contains like -
<html>test<abc>test2<adg>
它不会给我任何东西,请让我知道如何获得-
it will give me nothing please let me know how i can get-
testtest2
作为最终输出.
推荐答案
试试这个正则表达式:
<[^>]+>
演示:
http://regex101.com/r/kI5cJ7/2
讨论
将 html 代码放入一个字符串中,并将正则表达式应用于该字符串.
Put the html code in a string and apply to this string the regex.
var htmlCode = ...;
htmlCode = htmlCode.replace(/<[^>]+>/g, '');
原始正则表达式占用太多字符(*
是一个贪婪的运算符).
The original regex take too much characters (*
is a greedy operator).
查看此页面关于与 Star 和 Plus 重复,尤其是关于 Repetition with Star and Plus 的部分em>小心贪婪!".
Check this page about Repetition with Star and Plus, especially the part on "Watch Out for The Greediness!".
大多数不熟悉正则表达式的人会尝试使用 <.+>
.当他们在像 This is a <EM>first</EM> 这样的字符串上测试时,他们会感到惊讶.测试
.您可能希望正则表达式匹配 <EM>
并且在匹配之后继续时,</EM>
.
Most people new to regular expressions will attempt to use
<.+>
. They will be surprised when they test it on a string likeThis is a <EM>first</EM> test
. You might expect the regex to match<EM>
and when continuing after that match,</EM>
.
但事实并非如此.正则表达式将匹配 first
.显然不是我们想要的.
But it does not. The regex will match <EM>first</EM>
. Obviously not what we wanted.
这篇关于如何替换两个符号之间出现的所有字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!