.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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…