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?
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?
Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Aug 31, 2011 at 9:27 ThariamaThariama 50.8k13 gold badges145 silver badges174 bronze badges 1 |2 Answers
Reset to default 11As 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(/ [^ ]*$/));
The correct solution is not using a regex at all but the built-in lastIndexOf
method strings have. Regexes are meant to match strings, not give you indexes (even though grouped matchs may be returned as index+length instead of a string - C-based regex libraries usually do so to avoid unnecessary copying)
"str".lastIndexOf(' ')
? – Paul Commented Aug 31, 2011 at 9:29