Jump to content

javascript regular expression pattern from variable

Recommended Posts

Hello everyone,

Long time no sees I hope y'all fine,

I get some issue with regular expression if the pattern come from variable, these my codes

var data_code = $("#phone).attr('data-code');
var phone_number = '+61111111';

//if I use code like these :

 phone_number = phone_number.replace(/^\+61/,'');
// would return 11111111 === this is expected result

but when I tried

var pattern = "^'\'"+data_code; //I assumed this equal with : ^\+61
var regx = new RegExp(pattern,"g");
phone_number = phone_number.replace(regx,'');

would return '+61111111' in other there is no change,  my expectation it would return same if using usual pattern (^\+61),

in variable data_code have value = '+61'

Q : how to use regular expression's pattern from variable ?

please someone help me


Link to post
Share on other sites

From that code, it looks like your regular expression is ^''+61. You probably should remove those quotation marks and escape the backslash.

var pattern = "^\\" + data_code;


Link to post
Share on other sites
  • 3 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...