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 开发者_Python百科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?
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 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)
精彩评论