替代已弃用的RegExp。$ n对象属性 [英] Alternative to deprecated RegExp.$n object properties

查看:354
本文介绍了替代已弃用的RegExp。$ n对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用 RegExp $ n 属性( RegExp。$ 1 RegExp。$ 2 等)创建正则表达式单行。
这样的事情:

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

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

MDN文档说这些属性现已弃用。什么是更好的非弃用等价物?

The MDN docs say that these properties are now deprecated. What is a better non-deprecated equivalent?

推荐答案

.match / .exec



您可以存储RegEx在变量中并使用 .exec

var inputString = 'this is text that we must get';
var resultText = ( /\[([^\]]+)\]/.exec(inputString) || [] )[1] || "";
console.log(resultText); 

如何运作:

/\[([^\]]+)\]/.exec(inputString)

这将对字符串执行RegEx。它将返回一个数组。要访问 $ 1 ,我们访问数组的 1 元素。如果它不匹配,它将返回null而不是数组,如果它返回null,那么 || 将使它返回空数组 [] 所以我们不会收到错误。 || 是一个OR,所以如果第一面是假值(exec的未定义),它将返回另一面。

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.

你也可以使用匹配:

var inputString = 'this is text that we must get';
var resultText = ( inputString.match(/\[([^\]]+)\]/) || [] )[1] || "";
console.log(resultText); 



.replace



您可以使用。也替换:

.replace

You can use .replace also:

'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/,'$1');

如你所见,我添加了 ^。*?到RegEx的开头,。*?$ 到最后。然后我们用 $ 1 替换整个字符串,如果未定义 $ 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 :(';

你可以这样做:

'[this is the text]'.replace(/^.*?\[([^\]]+)\].*?$/, '$1' || 'No Matches :(');






如果您的字符串是多行的,请将 ^ [\\\\\ n] *?添加到字符串的开头,而 [^ \\\] *?$ 到最后


If your string in multiline, add ^[\S\s]*? to the beginning of the string instead and [^\S\s]*?$ to the end

这篇关于替代已弃用的RegExp。$ n对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆