An alternative to legacy RegExp object properties. $ N

I like to use the $n RegExp properties ( RegExp.$1 , RegExp.$2 , etc.) to create regular expressions with a single layer. Something like that:

 var inputString = '[this is text that we must get]'; var resultText = /\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : ''; console.log(resultText); 

MDN docs say these properties are now deprecated. What is the best non-obsolete equivalent?

+4
source share
1 answer

.match / .exec

You can save 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 it works:

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

This will execute RegEx on the line. It will return an array. To access $1 we get access to element 1 array. If it does not match, it will return null instead of an array, if it will return null, then || will make it a returnable empty array [] so that we don't get errors. || is OR, so if the first side is a false value (undefined exec), it will return the other side.

You can also use a match:

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

. Put on

You can also use .replace:

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

As you can see, I added ^.*? to the beginning of RegEx and .*?$ to the end. Then we replace the whole line with $1 , the line will be empty if $1 not defined. If you want to change "" to:

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

You can do:

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

If your string is in multi-line sequence, add ^[\S\s]*? to the beginning of the line and [^\S\s]*?$ to the end

+3
source

All Articles