Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

javascript - 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]';
var resultText = /[([^]]+)]/.test(inputString) ? RegExp.$1 : '';
console.log(resultText); 

The MDN docs say that these properties are now deprecated. What is a better non-deprecated equivalent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.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 ^[Ss]*? to the beginning of the string instead and [^Ss]*?$ to the end


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...