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
You can use
\bmetacharacter to set word boundaries: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
wordvariable. One possible solution is to use the following method: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:
DEMO: http://jsfiddle.net/ztYff/2/