2019-05-07
How to extract the last word in a string with a JavaScript regex?
源自: stackoverflow
问题

I need is the last match. In the case below the word test without the $ signs or any other special character:

Test String:

$this$ $is$ $a$ $test$ 

Regex:

\b(\w+)\b
答案
1

The $ represents the end of the string, so...

\b(\w+)$

However, your test string seems to have dollar sign delimiters, so if those are always there, then you can use that instead of \b.

\$(\w+)\$$

var s = "$this$ $is$ $a$ $test$"; 
 
document.body.textContent = /\$(\w+)\$$/.exec(s)[1];

If there could be trailing spaces, then add \s* before the end.

\$(\w+)\$\s*$

And finally, if there could be other non-word stuff at the end, then use \W* instead.

\b(\w+)\W*$
How to extract the last word in a string with a JavaScript regex?
查看原网页