简体   繁体   English

使用javascript匹配存储正则表达式的一部分

[英]Storing part of regex using javascript match

I want to find all #tags in a piece of text (using javascript) and use them. 我想在一段文本中找到所有#tags (使用javascript)并使用它们。 The regex myString.match(/#\\w+/g) works, but then I also get the #. 正则表达式myString.match(/#\\w+/g)有效,但我也得到了#。 How can I get only the word without the #? 如果没有#,我怎么才能得到这个词?

You can do something like this: 你可以这样做:

var code='...';
var patt=/#(\w+)/g;
var result=patt.exec(code);

while (result != null) {
    alert(result[1]);
    result = patt.exec(code);    
}

The ( and ) denote groups. ()表示组。 You can then access these groups and see what they contain. 然后,您可以访问这些组并查看它们包含的内容。 See here and here for additional information. 有关其他信息,请参见此处此处

var result = myString.match(/#\w+/g);
result.forEach(function (word, index, arr){
    arr[index] = word.slice(1);
});

Demo 演示

Note that I'm using ES5's forEach here. 请注意,我在这里使用ES5的forEach You can easily replace it with a for loop, so it looks like this: 您可以使用for循环轻松替换它,所以它看起来像这样:

var result = myString.match(/#\w+/g);
for (var i = 0; i < result.length; i++){
    result[i] = result[i].slice(1);
}

Demo without forEach 没有forEach的演示

Docs on forEach 关于forEach的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM