How to extract last word in string using javascript regular expression?

I need the last match. In the case below, a word testwithout characters $or other special characters:

Test line:

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

Regex:

\b(\w+)\b
+6
source share
4 answers

$ represents the end of the line, therefore ...

\b(\w+)$

However, your test string seems to have dollar sign delimiters, so if they always are, you can use this instead \b.

\$(\w+)\$$

var s = "$this$ $is$ $a$ $test$";

document.body.textContent = /\$(\w+)\$$/.exec(s)[1];
Run codeHide result

If there may be trailing spaces, add \s*to the end.

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

And finally, if at the end there may be other material without a word, then use \W*.

\b(\w+)\W*$
+11
source

var input = "$this$ $is$ $a$ $test$";

var result = input.match("\b(\w+)\b"), , , pop() : result[result.length]

0

, , .

A \w+ - , 1.
A \b - , -. '$'.

, $ .

To support input that can contain more than just a character '$'at the end of a line, spaces or a period, for example, you can use \w+one that matches as many non-alphanumeric characters as possible:

\$(\w+)\W+$
0
source

Avoid regular expressions - use .splitand .popresult. Use .replaceto remove special characters:

var match = str.split(' ').pop().replace(/[^\w\s]/gi, '');

Demo

0
source

Source: https://habr.com/ru/post/1688582/


All Articles