使用js将字符串中属于伪类的部分分离出来
时间: 2024-05-14 18:19:51 浏览: 12
,例如将 "div:hover {color: red;}" 中的 ":hover" 分离出来。
可以使用正则表达式来实现。以下是一个例子:
```
const str = "div:hover {color: red;}";
const pseudoClassRegex = /:(hover|active|focus|visited|link|after|before|checked|disabled|empty|enabled|first-child|first-letter|first-line|fullscreen|hover|indeterminate|in-range|invalid|last-child|last-of-type|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-of-type|only-child|optional|out-of-range|placeholder-shown|required|root|target|valid|visited)/g;
const pseudoClasses = str.match(pseudoClassRegex);
console.log(pseudoClasses); // [":hover"]
```
这段代码首先定义了一个字符串和一个正则表达式。正则表达式匹配所有可能的伪类,并使用`g`标志进行全局匹配。然后,`match()`方法应用正则表达式来查找字符串中的所有匹配项,并将它们存储在一个数组中。
在上面的例子中,匹配结果为`[":hover"]`。如果需要分离多个伪类,只需将它们按照竖线分隔并添加到正则表达式中即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)