ES6之与Symbol.match


ES6学习系列 😃


Symbol.match接受一个字符串类型的参数,如果匹配成功则返回匹配元素的数组,否则返回null。

The Symbol.match well-known symbol specifies the matching of a regular expression against a string. This function is called by the String.prototype.match() method.

对于String.prototype.startsWith(), String.prototype.endsWith()和String.prototype.includes()方法,会检查传入的第一个参数是否为正则表达式,如果是则会抛出异常。比如
在这里插入图片描述
由于这里的/foo/是一个正则表达式。所以抛出了异常。但如果设置该对象的Symbol.match属性为false

const regexp1 = /foo/;
regexp1[Symbol.match] = false;
// true
console.log('/foo/'.startsWith(regexp1));
// false	
console.log('/baz/'.endsWith(regexp1));

此时不会报错,而是正常执行。此处将Symbol.match设置为false用于标识当前对象不作为一个正则表达式对象。
在这里插入图片描述
更通常的用法是将Symbol.match用于字符串的匹配,设置为一个函数。比如

const str = "Hmm, this is interesting.";

str.match({
  [Symbol.match](str) {
    return ["Yes, it's interesting."];
  }
}); // returns ["Yes, it's interesting."]
  • match(regex) 确定给定字符串是否匹配正则表达式regex或者任何包含有Symbol.match方法的对象

The match() method retrieves the result of matching a string against a regular expression.

比如

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

// expected output: Array ["T", "I"]
console.log(found);

通常情况下,regexp的值是一个正则表达式对象,如上面所示。而返回值则取决于是否在正则表达式中包含有g(全局匹配)标签,如果没有匹配,则返回null。

  1. 当有全局匹配标签时,则返回一个数组,包含了所有匹配的结果。
/**
 * In the following example, match() is used to find "Chapter" followed by one or more numeric characters followed 
 * by a decimal point and numeric character zero or more times.The regular expression includes the i flag so that 
 * upper/lower case differences will be ignored.
 */
const str = 'For more information, see Chapter 3.4.5.1 ,see Chapter 3.4.5.2';
const re = /see (chapter \d+(\.\d)*)/gi;
const found = str.match(re);
/**
 * If the g flag is used, all results matching the complete regular expression will be returned, 
 * but capturing groups are not included.
 */
console.log(found);
// [
//   0 'see Chapter 3.4.5.1',
//   1 'see Chapter 3.4.5.2',
//   length: 2
// ]

在这里插入图片描述
2. 如果没有全局匹配标签时,则返回一个只包含第一个匹配结果和捕获组的数组。

/**
 * In the following example, match() is used to find "Chapter" followed by one or more numeric characters followed 
 * by a decimal point and numeric character zero or more times.The regular expression includes the i flag so that 
 * upper/lower case differences will be ignored.
 */
const str = 'For more information, see Chapter 3.4.5.1 ,see Chapter 3.4.5.2';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);
/**
 * If the g flag is not used, only the first complete match and its 
 * related capturing groups are returned. In this case, match() will return the same 
 * result as RegExp.prototype.exec() (an array with some extra properties).
 * 
 * In the match result above, 'see Chapter 3.4.5.1' is the whole match. 
 * 'Chapter 3.4.5.1' was captured by (chapter \d+(\.\d)*). 
 * '.1' was the last value captured by (\.\d). 
 * The index property (22) is the zero-based index of the whole match. 
 * The input property is the original string that was parsed.
 */
console.log(found);
// [
//   0: 'see Chapter 3.4.5.1',
//   1: 'Chapter 3.4.5.1',
//   2: '.1',
//   length: 3,
//   index: 22,
//   input: 'For more information, see Chapter 3.4.5.1',
//   groups: undefined
// ]

在这里插入图片描述
如果在match方法中不传递任何参数,将会返回一个包含一个空字符串的数组 [""],这种情况类似于匹配正则表达式(/(?:)/). 😃

const str = "Nothing will come of nothing.";
const found = str.match();   
// returns [""]
/**
	0: ""
	groups: undefined
	index: 0
	input: "Nothing will come of nothing."
	length: 1
 */
console.log(found);

除了正则表达式之外,其实还可以接受任何包含有Symbol.match方法的对象。

const str = "Hmm, this is interesting.";

const found = str.match({
  [Symbol.match](str) {
	return ["Yes, it's interesting."];
  }
}); 

// returns ["Yes, it's interesting."]
console.log(found);

如果既不是RegExp 对象,也不是包含有Symbol.match方法的对象,那么就会通过new RegExp(regexp)转为一个RegExp 对象。比如传入字符串和数组

const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.";
const str2 = "My grandfather is 65 years old and My grandmother is 63 years old.";
const str3 = "The contract was declared null and void.";
// "number" is a string. returns ["number"]
console.log(str1.match("number"));
// the type of NaN is the number. returns ["NaN"]
console.log(str1.match(NaN)); 
// the type of Infinity is the number. returns ["Infinity"]	   
console.log(str1.match(Infinity));
// returns ["Infinity"]
console.log(str1.match(+Infinity));
// returns ["-Infinity"]  
console.log(str1.match(-Infinity));
// returns ["65"]  
console.log(str2.match(65));
// A number with a positive sign. returns ["65"]		 
console.log(str2.match(+65));
// // returns ["null"]
console.log(str3.match(null));       

有时候需要注意转义问题,比如下面的.其实是匹配所有字符。

console.log("123".match("1.3")); // [ "123" ]

如果要正常匹配,要加上转义字符

console.log("123".match("1\\.3")); // null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lang20150928

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值