Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find last space character

I am looking for a regex that will give me the index of the last space in a string using javascript.

I was using goolge to find a suitable regex, but no success. Even the SO-Question Regex to match last space character does not hold a solution because the goal there was to remove more than one character in the end.

What is the correct regex?

like image 636
Thariama Avatar asked Aug 31 '11 09:08

Thariama


People also ask

How do you identify a space in regex?

Spaces can be found simply by putting a space character in your regex. Whitespace can be found with \s . If you want to find whitespace between words, use the \b word boundary marker.

Can regex include spaces?

Yes, also your regex will match if there are just spaces.


1 Answers

As I commented I would just use lastIndexOf() but here is a regex solution:

The regex / [^ ]*$/ finds the last space character in a string. Use it like this:

// Alerts 9
alert("this is a str".search(/ [^ ]*$/));
like image 186
Paul Avatar answered Oct 17 '22 03:10

Paul