Regex matches the last space character

I need help. I'm looking for a regex that matches the last space character in a string. I use JavaScript and classic ASP.

I have a long line of text that I trim to 100 characters. I would like to delete the last character in order to avoid spelling error if cropping shortens the word due to the 100 character limit.

regex.replace(/[ ]$.*?/ig, ''); 

Anyone with ideas? Thanks.

+6
javascript regex asp-classic
source share
5 answers

From my understanding, you need to remove the last space and everything after it, right?

  str = str.replace(/\s+\S*$/, "") 
+25
source share

Try the lookahead expression :

 / (?=[^ ]*$)/ 

And for arbitrary space characters:

 /\s(?=\S*$)/ 
+7
source share

This will

 / +$/ 

Space character ( ) at least once ( + ), at the end of the line ( $ )

Note that placing a space in a character class is not required if you do not want to match more than a space character, such as the [\t ] tabs.

To really match only one last space, use / $/


EDIT : cut everything after the last space (thinking about it, this is what you really think is necessary, you can use:

 regex.replace(/ +\S*$/ig, ''); 

where the regular expression means: "At least one space and any characters without spaces after it ( \S* ), at the end of the line ( $ ).".

This can only match the last bit of the line after the last space. As a side effect, the string is trimmed at the end.

+2
source share

The regular expression /^.+ [^ ]*$/ will only match the last space of the line.

+1
source share

Using the “classic” REs, what you want is " [^ ]*$" - that is, a space followed by an arbitrary number of non-spatial characters, followed by the end of the line. For example, “non-spatial characters” may or may not match your definition of a “word,” although, for example, it also prevents you from cutting the number in the middle. If you want to limit the word "word" to a letter, you can use " [^A-Za-z]*$" instead.

Also note that in any case, if the word ends exactly on the 100th character, this will correspond to the space before it, so you will delete this last whole word. If you want to prevent this, you probably want to look at the first character that you turned off, and if it's empty space, don't delete anything from the buffer.

0
source share

All Articles