[英]Javascript String Replace - RegEx for Non-Alphanumeric Characters Like Backslash, Greater Than, etc
I have a string that was serialized from the DOM world and I want to find some closing tags in that string and replace them with a new string. 我有一个从DOM世界序列化的字符串,我想在该字符串中找到一些结束标记,并用新字符串替换它们。 I never know the length of that original string, so character counts etc. will not work here.
我永远不知道原始字符串的长度,因此字符计数等在这里不起作用。 A sample scenario:
示例场景:
var onetext = "</content><tag>A whole bunch of stuff</tag></message>"
var twotext = "</content><tag>A whole bunch of new, unrelated stuff</tag></message>"
var threetext = onetext.replace(/[\/<]/\\/content>.+</message>/,"</content>"+twotext+"</message>");
I clearly don't have the regular expressions right to find these instances of backslash, greater-than or less-than. 我显然没有正则表达式来找到这些反斜杠的实例,大于或小于。 I welcome anyone's help in getting this to run correctly.
我欢迎任何人的帮助,让它正确运行。 Thanks.
谢谢。
If you want to capture everything that is NOT an allowed character, then write your expression for that. 如果你想捕获不是允许的字符的所有内容,那么为此编写表达式。
Here is an expression for that (keeps number, letter and spaces, rejects everything else): (?![a-zA-Z0-9 ]). 这是表达式(保留数字,字母和空格,拒绝其他所有内容):(?![a-zA-Z0-9])。
If you are looking for something specific to HTML tags, you want (catches open and close tags): 如果您正在寻找特定于HTML标记的内容,您需要(捕获打开和关闭标记):
([\\<]|[/>]) ([\\ <] | [/>])
Apparently, there is a way to do this with one line 显然,有一种方法可以用一行来做到这一点
You can use grouping identifiers in your replacements string like this: 您可以在替换字符串中使用分组标识符,如下所示:
'<foo>Some data</foo>'.replace(/(<foo>)(.+)(<\/foo>)/,'<bar>$2</bar>')
However, at the end of the day, if you ONLY want to replace closing tags, just replace those, don't worry about the rest of the content, unless you need to pass that through as well. 但是,在一天结束时,如果您只想替换结束标记,只需替换它们,不要担心其余内容,除非您也需要通过它。 If you are only looking at ... then this is the expression you need:
如果您只是在看......那么这就是您需要的表达方式:
/<\/content>.+<\/message>/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.