Skip to content Skip to sidebar Skip to footer

Alternative To Deprecated Regexp.$n Object Properties

I like using the $n properties of RegExp (RegExp.$1, RegExp.$2 etc) to create regular expression one-liners. Something like this: var inputString = '[this is text that we must get

Solution 1:

.match / .exec

You can store the RegEx in a variable and use .exec:

var inputString = 'this is text that we must get';
var resultText = ( /\[([^\]]+)\]/.exec(inputString) || [] )[1] || "";
console.log(resultText); 

How this works:

/\[([^\]]+)\]/.exec(inputString)

This will execute the RegEx on the string. It will return an array. To access $1 we access the 1 element of the array. If it didn't match, it will return null instead of an array, if it returns null, then the || will make it return blank array [] so we don't get errors. The || is an OR so if the first side is a falsey value (the undefined of the exec) it will return the other side.

You can also use match:

var inputString = 'this is text that we must get';
var resultText = ( inputString.match(/\[([^\]]+)\]/) || [] )[1] || "";
console.log(resultText); 

.replace

You can use .replace also:

'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/,'$1');

As you can see, I've added ^.*? to the beginning of the RegEx, and .*?$ to the end. Then we replace the whole string with $1, the string will be blank if $1 isn't defined. If you want to change the "" to:

/\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : 'No Matches :(';

You can do:

'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/, '$1' || 'No Matches :(');

If your string in multiline, add ^[\S\s]*? to the beginning of the string instead and [^\S\s]*?$ to the end

Post a Comment for "Alternative To Deprecated Regexp.$n Object Properties"