3

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;
3
  • Not really less hacky but you can tidy by chaining lines 1 with 2 and 3 with 4. Commented Nov 25, 2014 at 20:36
  • 1
    You can get the regex with .source(), but this is a read-only property. You'd have to make a new regex object. Commented Nov 25, 2014 at 20:37
  • ....typo in line 3? Should stripcharsre be regex? Commented Nov 25, 2014 at 20:39

2 Answers 2

4

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, '') );

Sign up to request clarification or add additional context in comments.

3 Comments

Great - .source will be what I'm looking for. Nice work with the positive-lookahead too - thanks!
You can also figure out if the regex is global and case sensitive, instead of duplicating the gi flags
@JuanMendes Yes, it's true, we can check global and ignoreCase properties.
0

Here's a generic way to add a character class to any regular expression

function addCharacterClass(regex, string) {
    var flags = (regex.global ? "g" : "" ) + (regex.ignoreCase ? "i" : "" )
    return new RegExp(regex.source + "|([" + string + "])", flags);
}

document.getElementById('check').addEventListener('click', function(){
   var originalRegex = new RegExp(document.getElementById('regex').value);
   var additionalChars = document.getElementById('chars').value;
   var testString = document.getElementById('test-string').value;
   alert("Does regex match? " + addCharacterClass(originalRegex, additionalChars).test(testString) );
  
});
Original Regex: <input id="regex" value="[^0123456789.-]" /> <br />
Additional Characters: <input id="chars" value="£$€"/> <br />
Test string <input id="test-string" value="$123456"> <br />
<button id="check">Check</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.