如何用Javascript在字符串中获取一些单词?

时间:2018-03-28 11:13:17

标签: javascript regex

我想删除'(*)'之外的所有字符。 如何为结果创建代码?

string = "hello (hi) this (is) my (questions)";
=> "(hi)(is)(questions)"

3 个答案:

答案 0 :(得分:0)

此正则表达式选择不在(*)\(+\w+\)

之外的字符

答案 1 :(得分:0)

使用match(内联评论)

var string = "hello (hi) this (is) my (questions)";

var matches = string.match(/\([^)]*\)/g); //match all those string which begins with ( and end with ) and there is no ) in between

var output = matches ? matches.join( "" ) : ""; //check if there is any match

console.log ( output );

答案 2 :(得分:0)

简单的方法是与\((.*?)\)匹配,后者会为您提供匹配的单词数组,然后join使用''

var string = "hello (hi) this (is) my (questions)";
var matched = string.match(/\((.*?)\)/g);
matched = matched.join('');
console.log(matched);