我正在尝试在 JS 中创建一个正则表达式,它将匹配 box
的出现并返回完整的复合词
使用字符串:
the box which is contained within a box-wrap has a box-button
我想得到:
[box, box-wrap, box-button]
是否可以仅使用字符串 box
来匹配这些单词?
这是我到目前为止所尝试过的,但它没有返回我想要的结果。
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
最佳答案
试试这个方法:
([\w-]*box[\w-]*)
<小时/>
根据评论的要求,这里是一个 javascript 的工作示例:
function my_search(word, sentence) {
var pattern = new RegExp("([\\w-]*" + word + "[\\w-]*)", "gi");
sentence.replace(pattern, function(match) {
document.write(match + "<br>"); // here you can do what do you want
return match;
});
};
var phrase = "the box which is contained within a box-wrap " +
"has a box-button. it is inbox...";
my_search("box", phrase);
希望有帮助。
关于javascript - 正则表达式仅使用第一个单词来匹配复合词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812053/