2

So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.

Possible inputs might be:

\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text

Only the first and the third line should be affected by this function. Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.

I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.

Bas Pauw
  • 262
  • 1
  • 12
  • 1
    Possible duplicate of [RTrim in javascript](https://stackoverflow.com/questions/8791394/rtrim-in-javascript) – Amit Kumar Singh Oct 24 '17 at 14:47
  • does the order of `\r` and `\n` matter or are you looking to replace just `\r\n` in that order, at the end of the line? – Joseph Marikle Oct 24 '17 at 14:51
  • @JosephMarikle It represent a breakline (if I'm correct) in Windows, so it should be the seuqence – Bas Pauw Oct 24 '17 at 14:53
  • Alright. That makes sense. If it were a more generic newline replacement I would have suggested a character class instead, but it sounds like this is a very specific use case. – Joseph Marikle Oct 24 '17 at 15:01
  • Question says `ltrim` and `rtrim` but description says only `rtrim`. What is correct? – anubhava Oct 24 '17 at 15:03

1 Answers1

2

You can use the following piece of code to do that for you:

var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');

Here, $ matches end of input.

You can refer to the regular expressions guide here to find out more about regex in JS.

EDIT:

If you really need a function for this:

var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
    return input.replace(rTrimRegex, '');
}

And then use it inside your code maybe like:

var str = 'my name is foo\r\n\r\n';
str = rTrim(str);
Parijat Purohit
  • 921
  • 6
  • 16
  • 1
    I was more thinking in a way of `str.rtrim('\r\n')` but your code works flawless! Thanks a lot! – Bas Pauw Oct 24 '17 at 15:09
  • @BasPauw oh okay. Glad I could help. You can browse through other regex special characters and their uses as well, might help a lot. – Parijat Purohit Oct 24 '17 at 15:12