Thariama
Thariama

Reputation: 50832

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?

Upvotes: 6

Views: 9280

Answers (2)

Paul
Paul

Reputation: 141839

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(/ [^ ]*$/));

Upvotes: 11

ThiefMaster
ThiefMaster

Reputation: 318498

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)

Upvotes: 8

Related Questions