usumoio
usumoio

Reputation: 3568

Regular Expression for last value in comma separated list

I am trying to build a regular expression that returns everything after the last comma in a comma separated list.

// So if my list is as followed
var tag_string = "red, green, blue";

// Then my match function would return
var last_tag = tag_string.match(A_REGEX_I_CANNOT_FIGURE_OUT_YET);

// Then in last tag I should have access to blue

// I have tried the following things: 
var last_tag = tag_string.match(",\*");

// I have seen similar solutions, but I cannot figure out how to get the only the last string after the last comma.

Upvotes: 2

Views: 4228

Answers (4)

jik777
jik777

Reputation: 61

tag_string.match(/[^,\s]+$/)

=> [ 'blue', index: 12, input: 'red, green, blue' ]

Thats it :)

Upvotes: -1

progrenhard
progrenhard

Reputation: 2363

([^,]+)$

Regular expression visualization

Edit live on Debuggex

Upvotes: 3

user1508519
user1508519

Reputation:

[^,]+$

seems to do the trick. It matches blue.

Upvotes: 2

Jerry
Jerry

Reputation: 71538

You can try something like:

var last_tag = tag_string.match("[^,]+$").trim();

This will first get " blue" then remove the trailing spaces.

Upvotes: 7

Related Questions