如何在Javascript中删除所有带“ - ”的单词

时间:2017-04-11 09:25:38

标签: javascript regex

我对regex完全不熟悉,也无法弄清楚如何通过Javascript实现它。

例如,我有字符串var string = "-just an example -string for stackoverflow"。预期结果为string = "an example for stackoverflow"

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个:

-\w+\s+

并替换为空

Regex Demo

const regex = /-\w+\s+/gm;
const str = `-just an example -string for stackoverflow`;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);

答案 1 :(得分:0)

使用简单的forEach尝试此操作。



var string = "-just an example -string for stackoverflow";
var strArray = string.split(' ');
strArray.forEach(function(value, i){
  if(value.startsWith('-')){
    strArray.splice( i, 1 )
  }
});
console.log(strArray.join(' '));