A regular expression to capture characters between the last space character and the end of a line

I am trying to identify the characters between the last space character and the end of a line.

Example

Input: "this and that" Output: "that" 

I tried the regex below, but it doesn't work!

 var regex = /[\s]$/ 
+4
source share
4 answers

You can do without regex

 var result = string.substring(string.lastIndexOf(" ")+1); 

Using regex

 result = string.match(/\s[az]+$/i)[0].trim(); 
+7
source

I suggest you use a simple regex pattern

 \S+$ 

Javascript validation code:

 document.writeln("this and that".match(/\S+$/)); 

Output:

 that 

Check here .

+1
source

You can simply delete everything to the last place.

 s.replace(/.* /, '') 

Or, to match any space ...

 s.replace(/.*\s/, '') 
0
source

In your example, there is only one space at the end of the line. Use

 /\s\S+$/ 

to match any number.

-1
source

Source: https://habr.com/ru/post/1442514/


All Articles