我喜欢使用(等)$n的属性来创建正则表达式单行代码。像这样的东西:RegExpRegExp.$1RegExp.$2
var inputString = '[this is text that we must get]';
var resultText = /\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : '';
console.log(resultText);
Run Code Online (Sandbox Code Playgroud)
MDN 文档说这些属性现在已被弃用。什么是更好的未弃用的等效项?
您可以将正则表达式存储在变量中并使用.exec:
var inputString = 'this is text that we must get';
var resultText = ( /\[([^\]]+)\]/.exec(inputString) || [] )[1] || "";
console.log(resultText);
Run Code Online (Sandbox Code Playgroud)
这是如何运作的:
/\[([^\]]+)\]/.exec(inputString)
Run Code Online (Sandbox Code Playgroud)
这将在字符串上执行正则表达式。它将返回一个数组。为了访问$1我们访问1数组的元素。如果不匹配,它将返回 null 而不是数组,如果返回 null,则将||使其返回空白数组[],这样我们就不会收到错误。这||是一个 OR,因此如果第一边是 false 值(exec 的未定义),它将返回另一边。
您还可以使用匹配:
var inputString = 'this is text that we must get';
var resultText = ( inputString.match(/\[([^\]]+)\]/) || [] )[1] || "";
console.log(resultText);
Run Code Online (Sandbox Code Playgroud)
您也可以使用 .replace :
'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/,'$1');
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我已添加^.*?到正则表达式的开头和.*?$结尾。然后我们将整个字符串替换为,如果没有定义,$1该字符串将为空。$1如果您想将其更改""为:
/\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : 'No Matches :(';
Run Code Online (Sandbox Code Playgroud)
你可以做:
'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/, '$1' || 'No Matches :(');
Run Code Online (Sandbox Code Playgroud)
如果您的字符串是多行的,请添加^[\S\s]*?到字符串的开头和[^\S\s]*?$结尾
| 归档时间: |
|
| 查看次数: |
2074 次 |
| 最近记录: |