javascript replace()不替换包含文字\r\\\<br/>字符串的文本 [英] javascript replace() not replacing text containing literal \r\n strings
问题描述
value = value.replace(/ [\r\\\
] * / g,);
但是当代码实际上包含\r\\\
文本时,影响我的内容中的r和n?我试过这个代码:
value = value.replace(/ [\\\\\
] + / g,);
在这一段文字上:
{client:{werdfasreasfsd:asdfRasdfas\rr\\\
MCwwDQYJKoZIhvcNAQEBBQADGw ......
我结束了这一点:
{cliet:{wedfaseasfsd :asdfRasdfasMCwwDQYJKoZIhvcNAQEBBQADGw ......
旁注:它留下大写版本的R和N单独,因为我没有包括/ i标志在这个结束,这是确定在这种情况。
我该怎么做只是删除\
如果你想匹配文字 \r
和文字 \\\
然后您应该使用以下内容:
value = value.replace(/(?: \\ [rn])+ / g,);
您可能会认为匹配的文字 \r
和 \\\
与
[\\\\\\
是正确的方式它有点混乱,但它不会工作,这里是为什么:
]
请记住,在字符类中,每个单个字符表示单个字母或符号,它不代表一个字符序列,它只是一个设置的字符。
所以角色类 [ \\\\\\
实际匹配文字字符
] \
, r
和 n
作为单独的字母而不是序列。
编辑:如果要替换所有回车符 \r
,换行符 \\\
还有文字
\r
和'\\\
`,则可以使用:
value = value。替换(/(?:\\ [rn] | [\r\\\
] +)+ / g,);
关于(?:)
这意味着因为默认情况下,当您将某些东西放入通常的组()
中时,它会被捕获到一个编号的变量中,您可以在正则表达式中的其他位置使用它,或者后者在匹配数组中。
(?:)
阻止捕获该值并导致比()
,有关详细信息,请参阅本文。
Using this bit of code trims out hidden characters like carriage returns and linefeeds with nothing using javascript just fine:
value = value.replace(/[\r\n]*/g, "");
but when the code actually contains \r\n text what do I do to trim it without affecting r's and n's in my content? I've tried this code:
value = value.replace(/[\\r\\n]+/g, "");
on this bit of text:
{"client":{"werdfasreasfsd":"asdfRasdfas\r\nMCwwDQYJKoZIhvcNAQEBBQADGw......
I end up with this:
{"cliet":{"wedfaseasfsd":"asdfRasdfasMCwwDQYJKoZIhvcNAQEBBQADGw......
Side note: It leaves the upper case versions of R and N alone because I didn't include the /i flag at the end and thats ok in this case.
What do I do to just remove \r\n text found in the string?
If you want to match literal \r
and literal \n
then you should use the following:
value = value.replace(/(?:\\[rn])+/g, "");
You might think that matching literal \r
and \n
with [\\r\\n]
is the right way to do it and it is a bit confusing but it won't work and here is why:
Remember that in character classes, each single character represents a single letter or symbol, it doesn't represent a sequence of characters, it is just a set of characters.
So the character class [\\r\\n]
actually matches the literal characters \
, r
and n
as separate letters and not as sequences.
Edit: If you want to replace all carriage returns \r
, newlines \n
and also literal \r
and '\n` then you could use:
value = value.replace(/(?:\\[rn]|[\r\n]+)+/g, "");
About (?:)
it means a non-capturing group, because by default when you put something into a usual group ()
then it gets captured into a numbered variable that you can use elsewhere inside the regular expression itself, or latter in the matches array.
(?:)
prevents capturing the value and causes less overhead than ()
, for more info see this article.
这篇关于javascript replace()不替换包含文字\r\\\<br/>字符串的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!