1252748
1252748

Reputation: 15372

find single or multiple \n at the end of a string

I'm trying to capture the values of a tab separated list:

1   11  11111111
2   22  2222
3   33  33333333

It is pretty straightforward except that the last line could have a trailing \n which gives me some errors when I loop through the lines in other areas of my script. If it has this trailing \n, I would like to get rid of it. I could do this:

var res = myStr.substr(-1);
if (/\n/.test(res)){
    return myStr.substr(0, myStr.length - 1)
}

But of course this will fail to truncate a string with multiple trailing \n. I suppose I could loop through with the substring approach until the last character isn't an \n, however I wonder if there's a more elegant regex approach.

/^\s*[\r\n]/gm.test(myStr)

for some reason only returns true when there is more than one \n at the end of the string, and returns false when there is exactly one \n.

I thought to use the jquery $.trim() method, but it will truncate the last line if it is only tabs. I can't do this because I still want to keep account of the presence of that line even if it is empty.

Not that the loop is a totally unsupportable idea, but is there a way to solve this with a regex?

Upvotes: 0

Views: 66

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

If you want to get rid of it then try

myTest = $.trim(myText)

Note: It will remove empty spaces also

else try testing /\n+$/.test(myText)

Upvotes: 0

Kita
Kita

Reputation: 2634

I think you are looking for:

var result = yourString.replace(/\n+$/,"");

In regex basics,

  • + is a quantifier for "1 or more occurrences of previous character"
  • $ is "the end position of string" anchor.

Upvotes: 2

Related Questions