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?
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)
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(/ [^ ]*$/));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.