我喜欢使用RegExp
的$n
属性(例如RegExp.$1
、RegExp.$2
等)来创建正则表达式一行代码。
像这样:
var inputString = '[this is text that we must get]';
var resultText = /\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : '';
console.log(resultText);
MDN文档称这些属性现在已经被弃用。有没有更好的非弃用替代品?
我喜欢使用RegExp
的$n
属性(例如RegExp.$1
、RegExp.$2
等)来创建正则表达式一行代码。
像这样:
var inputString = '[this is text that we must get]';
var resultText = /\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : '';
console.log(resultText);
MDN文档称这些属性现在已经被弃用。有没有更好的非弃用替代品?
您可以将正则表达式存储在变量中,然后使用.exec
:
var inputString = 'this is text that we must get';
var resultText = ( /\[([^\]]+)\]/.exec(inputString) || [] )[1] || "";
console.log(resultText);
这是如何工作的:
/\[([^\]]+)\]/.exec(inputString)
$1
,我们要访问数组的第1
个元素。如果没有匹配,则返回null而不是数组,如果返回null,则||
将使其返回空数组[]
,以避免出现错误。 ||
是一个OR,因此如果第一侧是假值(exec的未定义),它将返回另一侧。var inputString = 'this is text that we must get';
var resultText = ( inputString.match(/\[([^\]]+)\]/) || [] )[1] || "";
console.log(resultText);
您也可以使用.replace:
'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/,'$1');
如您所见,我已将^.*?
添加到RegEx的开头,并将.*?$
添加到结尾。 然后,我们用$1
替换整个字符串,如果$1
未定义,则该字符串将为空。 如果您想将""
更改为:
/\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : 'No Matches :(';
您可以做:
'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/, '$1' || 'No Matches :(');
^[\S\s]*?
,在结尾添加[^\S\s]*?$
。.replace
版本。 - DowngoatString.prototype.match()
呢?inputString.match(/\[([^\]]+)\]/)[1]
- Jan(вҖҰ || [,""])[1]
жқҘд»Јжӣҝ(вҖҰ || [])[1] || ""
- Bergi
$1-9
属性,因为它们总是不可靠的。 - adeneo