简体   繁体   English

解释用于从String中删除html代码的正则表达式

[英]Explain regular expression for removing html code from String

I have a regular expression which removes html code from a String : 我有一个正则表达式从字符串中删除html代码:

var html = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";

text = html.replace(/(<([^>]+)>)/ig, "")

alert(text)

This is the expression working on jsfiddle : http://jsfiddle.net/VgHr3/53/ 这是jsfiddle上的表达式: http//jsfiddle.net/VgHr3/53/

The regular expression itself is /(<([^>]+)>)/ig . 正则表达式本身是/(<([^>]+)>)/ig I don't fully understand how this expression works. 我不完全理解这个表达式是如何工作的。 Can provide an explanation ? 可以提供解释吗? I can find what each character by itself behaves by reading a cheatsheet : http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ 通过阅读备忘单,我可以找到每个角色本身的行为: http//www.cheatography.com/davechild/cheat-sheets/regular-expressions/

But what is the significance of "/ig" ? 但是“/ ig”的意义是什么?

Those are global flags. 那些是全球旗帜。 Your cheat sheet actually lists them on the right side: 你的备忘单实际上是在右侧列出的:

Regular Expressions Pattern Modifiers
g   Global match
i   Case-i­nse­nsitive
m   Multiple lines
s   Treat string as single line
x   Allow comments and white space in pattern
e   Evaluate replac­ement
U   Ungreedy pattern

Note that not all of these flags are supported by the JavaScript regular expression engine. 请注意,JavaScript正则表达式引擎并不支持所有这些标志。 For an authoritative list, see this MDN article . 有关权威列表,请参阅此MDN文章

So the "g" flag makes it global, so it replaces this pattern wherever it is found, instead of just the first instance (which is the default behavior of the replace method). 因此“g”标志使其成为全局标志,因此无论在何处找到它都会替换此模式,而不仅仅是第一个实例(这是replace方法的默认行为)。

The "i" flag makes it case-insensitive, so a pattern like [az]+ will match "foo" and "FOO" . “i”标志使其不区分大小写,因此像[az]+这样的模式将匹配"foo""FOO" However, because your pattern only involves < and > characters, this flag is useless. 但是,因为您的模式只涉及<>字符,所以此标志无用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM