Jump to content

javascript regular expression pattern from variable


gongpex
 Share

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.

Link to comment
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 comment
Share on other sites

  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...