Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

regex - javascript replace() not replacing text containing literal strings

Using this bit of code trims out hidden characters like carriage returns and linefeeds with nothing using javascript just fine:

value = value.replace(/[
]*/g, "");

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, "");

on this bit of text:

{"client":{"werdfasreasfsd":"asdfRasdfas
MCwwDQYJKoZIhvcNAQEBBQADGw......

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 text found in the string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to match literal and literal then you should use the following:

value = value.replace(/(?:\[rn])+/g, "");

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.

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 , newlines and also literal and ' ` then you could use:

value = value.replace(/(?:\[rn]|[
]+)+/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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...