Jump to content
Sign in to follow this  
gongpex

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/,'');
console.log(phone_number)
// 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

Thanks.

Share this post


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;

 

Share this post


Link to post
Share on other sites

in your code you have try with this code

phone_number = phone_number.replace("^(?:(?:\+|0{0,2})61(\s*[\-]\s*)?|[0-9]?)?[]\d{7}$")

 

Share this post


Link to post
Share on other sites

Join the conversation

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

Guest
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.

Loading...
Sign in to follow this  

×
×
  • Create New...