我该如何创建一个可以选择不以'#'或'。'开头的单词的正则表达式。

时间:2019-03-26 23:52:28

标签: javascript regex

我想创建一个JavaScript函数,该函数可以浏览一串CSS选择器,并从其他选择器(例如ID和类)中选择标记名称(body,p,h1)的元素(#test .test1 )

一个例子是字符串: “ span#a53195yio1rnin6d2t9 div.first”

只返回span和div,其余的保留

这是我到目前为止所拥有的,但是它会选择'#'或'。'之后的所有内容。

(\ b(?!#|!。)\ w +)\ b

1 个答案:

答案 0 :(得分:3)

如果您的环境支持向后搜索,则只需向后搜索空格或行首:

const str = "span#a53195yio1rnin6d2t9 div.first";
console.log(
  str.match(/(?:^|(?<= ))\w+/gm)
);

否则,如果必须支持较旧的浏览器,则必须手动遍历匹配项- match 字符串或空格的开头,然后是 capture 组中的下一个单词字符,然后提取该捕获组:

const str = "span#a53195yio1rnin6d2t9 div.first";
const re = /(?:^| )(\w+)/gm;
const matches = [];
let match;
while (match = re.exec(str)) {
  matches.push(match[1]);
}
console.log(matches);

相关问题