废弃的RegExp.$n对象属性的替代方案

7

我喜欢使用RegExp$n属性(例如RegExp.$1RegExp.$2等)来创建正则表达式一行代码。 像这样:

var inputString = '[this is text that we must get]';
var resultText = /\[([^\]]+)\]/.test(inputString) ? RegExp.$1 : '';
console.log(resultText); 

MDN文档称这些属性现在已经被弃用。有没有更好的非弃用替代品?


3
这不应该相当简单明了吗?毕竟很少有人真正使用$1-9属性,因为它们总是不可靠的。 - adeneo
哇,我从未见过有人在实际应用中使用这些。 - Bergi
1个回答

4

.match / .exec

您可以将正则表达式存储在变量中,然后使用.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的未定义),它将返回另一侧。
您还可以使用match:
var inputString = 'this is text that we must get';
var resultText = ( inputString.match(/\[([^\]]+)\]/) || [] )[1] || "";
console.log(resultText); 

.replace

您也可以使用.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]*?$

1
@GeorgiNaumov 已修复 :) - Downgoat
1
@GeorgiNaumov 如果这对您不起作用,我已经添加了一个.replace版本。 - Downgoat
1
为什么不直接使用 String.prototype.match() 呢?inputString.match(/\[([^\]]+)\]/)[1] - Jan
我发起这个问题是为了收集想法。 - Georgi Naumov
1
дҪ еҸҜиғҪжғіиҰҒдҪҝз”Ё(вҖҰ || [,""])[1]жқҘд»Јжӣҝ(вҖҰ || [])[1] || "" - Bergi
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接