Jack
Jack

Reputation: 7557

Javascript match function

How do I give expression inside match function in javascript?

Eg.

var val = $('#somElement').val();
var startWith = '#'
var match = val.match('/(\s)?' + startWith + '(.*?)(\s+|$)/'g);

The match function takes in a parameter without string and hence the above line is wrong. How do I change it so that I can give in the parameter to val.match dynamically based on my variable's value?

Upvotes: 1

Views: 992

Answers (1)

Pointy
Pointy

Reputation: 414076

You need to explicitly construct a RegExp object:

var match = val.match( new RegExp('(\\s)?' + startWith + '(.*?)(\\s+|$)', 'g') );

Note that backslashes need to be doubled, to account for the fact that the string constant syntax also uses backslashes for special-character quoting, and that you don't need the leading and trailing forward-slash.

Upvotes: 4

Related Questions