【问题标题】:How to delete all words with "-" before in Javascript [duplicate]如何在Javascript中删除所有带有“-”的单词[重复]
【发布时间】:2017-04-11 17:46:00
【问题描述】:

我对正则表达式完全陌生,不知道如何通过 Javascript 实现它。

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

提前致谢

【问题讨论】:

  • 你试过什么?你能显示一些代码吗
  • 拥有 1K+ 代表,您应该知道如何努力创建minimal reproducible example。例如在 google 中搜索 javascript regex 查找并替换以 开头的单词 - 花了我
  • str = str.replace(/(-\S+)/g,"")

标签: javascript regex


【解决方案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);

【讨论】:

    【解决方案2】:

    用简单的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(' '));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2011-11-29
      • 2021-10-03
      相关资源
      最近更新 更多