Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  160] [ 2]  / answers: 1 / hits: 60186  / 11 Years ago, sat, november 16, 2013, 12:00:00

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



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


but when the code actually contains rn 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:asdfRasdfasrnMCwwDQYJKoZIhvcNAQEBBQADGw......


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


More From » regex

 Answers
1

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]|[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.


[#74245] Friday, November 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;