RichardB
RichardB

Reputation: 339

Javascript Regex For Comma Delimited String

I need a regex expression that performs a "contains" function on a input/type=hidden field's value. This hidden field stores unique values in a comma delimited string.

Here's a scenario.
The value: "mix" needs to be added to the hidden field. It will only be added if it does not exist as a comma delimited value.

With my limited knowlege of regex, I can't prevent the search from returning all ocurrences of the "mix" value. For example if: hiddenField.val = 'mixer, mixon, mixx', the regex always returns true, because the all three words contain the "mix" characters.

Thanks in advance for the help

Upvotes: 1

Views: 3334

Answers (4)

VisioN
VisioN

Reputation: 145458

You can use \b metacharacter to set word boundaries:

var word = "mix";
new RegExp("\\b" + word + "\\b").test(hidden.value);

DEMO: http://jsfiddle.net/ztYff/


UPDATE. In order to protect our regular expression of possible problems when using variable instead of hardcoding (see comments below), we need to escape special characters in word variable. One possible solution is to use the following method:

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

DEMO: http://jsfiddle.net/ztYff/1/


UPDATE 2. Following @Porco's answer we can combine regular expressions and string splitting to get another universal solution:

hidden.value.split(/\s*,\s*/).indexOf(word) != -1;

DEMO: http://jsfiddle.net/ztYff/2/

Upvotes: 3

Porco
Porco

Reputation: 4203

hiddenField.val.split(',').indexOf('mix') >= 0

Could also use a regex(startofstring OR comma + mix + endofstring OR comma):

hiddenField.val.match(/(,|^)mix($|,)/)

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817030

How about:

/(^|,)\s*mix\s*(,|$)/.test(field.value)

It matches mix, either if it is at the beginning of a string or at the end or in between commas. If each entry in the list can consist of multiple words, you might want to remove the \s*.

Upvotes: 0

Danilo Valente
Danilo Valente

Reputation: 11352

hiddenField.val.match(/^(mix)[^,]*/);

Upvotes: 0

Related Questions