Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Add to a RegEx

I'm working with a library which specifies a RegEx on an object. I need to add some characters into that RegEx. Is there a less hacky way of doing this?

I have no control over this.stripCharsRegex.

// this.stripCharsRegex =   /[^0123456789.-]/gi
var regexChars = this.stripCharsRegex.toString();
regexChars = regexChars.substr(3,regex.length-7);  // remove '/[^'  and   ']/gi'
var regex = new RegExp('[^£$€'+regexChars+']','gi');  // (e.g.)
this.stripCharsRegex = regex;
like image 516
Dave Salomon Avatar asked Mar 04 '26 18:03

Dave Salomon


1 Answers

I think you should be able to combine new regexp rule with old RegExp object if you use its source property. Try this:

this.stripCharsRegex = new RegExp('(?=[^£$€])' + this.stripCharsRegex.source, 'gi');

Check test snippet below.

var stripCharsRegex = new RegExp('[^0123456789.-]', 'gi');

alert( 'Total: $123 test - £80&dd'.replace(stripCharsRegex, '') );

// extend regexp by creating new RegExp object
stripCharsRegex = new RegExp('(?=[^£$€])' + stripCharsRegex.source, 'gi');

alert( 'Total: $123 test - £80&dd'.replace(stripCharsRegex, '') );
like image 126
dfsq Avatar answered Mar 07 '26 09:03

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!