最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to find last space character - Stack Overflow

programmeradmin1浏览0评论

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
  • 3 You can't use "str".lastIndexOf(' ')? – Paul Commented Aug 31, 2011 at 9:29
Add a comment  | 

2 Answers 2

Reset to default 11

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)

发布评论

评论列表(0)

  1. 暂无评论