Alternative to deprecated RegExp.$n object properties

后端 未结 1 604
梦谈多话
梦谈多话 2020-12-11 20:48

I like using the $n properties of RegExp (RegExp.$1, RegExp.$2 etc) to create regular expression one-liners. Something li

相关标签:
1条回答
  • 2020-12-11 21:47

    .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

    0 讨论(0)
提交回复
热议问题