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

Categories

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

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

1 Answer

.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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...