javascript replace() 不替换包含文字 字符串的文本 [英] javascript replace() not replacing text containing literal strings
问题描述
使用这段代码可以去掉隐藏字符,如回车和换行符,而无需使用 javascript 就好了:
Using this bit of code trims out hidden characters like carriage returns and linefeeds with nothing using javascript just fine:
value = value.replace(/[
]*/g, "");
但是当代码实际上包含 文本时,我该怎么做才能在不影响内容中的 r 和 n 的情况下修剪它?我试过这个代码:
but when the code actually contains 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, "");
关于这段文字:
{"client":{"werdfasreasfsd":"asdfRasdfas
MCwwDQYJKoZIhvcNAQEBBQADGw......
我最终是这样的:
{"cliet":{"wedfaseasfsd":"asdfRasdfasMCwwDQYJKoZIhvcNAQEBBQADGw......
旁注:它保留了 R 和 N 的大写版本,因为我没有在末尾包含/i 标志,在这种情况下没问题.
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 text found in the string?
推荐答案
如果你想匹配文字
和文字
那么你应该使用以下内容:
If you want to match literal
and literal
then you should use the following:
value = value.replace(/(?:\[rn])+/g, "");
您可能认为将文字
和
与 [\r\n]
匹配是正确的做法它有点令人困惑,但它不起作用,原因如下:
You might think that matching literal
and
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.
所以字符类 [\r\n]
实际上匹配文字字符 、
r
和 n
作为单独的字母而不是序列.
So the character class [\r\n]
actually matches the literal characters ,
r
and n
as separate letters and not as sequences.
如果你想替换所有回车
、换行符
和文字
和 '
` 那么你可以使用:
If you want to replace all carriage returns
, newlines
and also literal
and '
` then you could use:
value = value.replace(/(?:\[rn]|[
]+)+/g, "");
About (?:)
这意味着一个非捕获组,因为默认情况下,当你把一些东西放入一个普通的组 ()
然后它被捕获到一个编号中您可以在正则表达式本身的其他地方使用的变量,或者在匹配数组中使用.
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() 不替换包含文字 字符串的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!