【问题标题】:Javascript - Using .replace to remove the word "and" from stringJavascript - 使用 .replace 从字符串中删除单词“and”
【发布时间】:2020-08-03 19:34:25
【问题描述】:

我有一个字符串,我正试图从中删除单词“and”。我正在尝试通过在 javascript 中使用 .replace 方法。我可以删除“和”这个词,但最终结果不是我所期望的。

我希望我的字符串返回类似于console.log(testString),其中整个字符串返回为"i-have-a-test-test-test",中间没有任何空格。目前,我对console.log(newString) 的尝试返回的字符串在每个单词之间没有-

我的预期结果是返回结果为:

I-have-a-test-test-test

const string = "I have a test and test and test" 

const newString = string.replace(/([^a-zA-Z0-9]*|\s*)\s\and/g, '-')

const testString = string.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-')
console.log(newString)
console.log(testString)

【问题讨论】:

标签: javascript string


【解决方案1】:
var s = "I have a test and test and test" 
s = s.replace(/ and /g, '-').replace(/ /g, '-')

var s = "I have a test and test and test" 
s = s.replace(/ and | /g, '-')

【讨论】:

    【解决方案2】:

    const string = "I have a test and test and test"; 
    const string2= string.split(" ").join("-").split("and").join("").split("--").join("-");
    console.log(string2)

    【讨论】:

      【解决方案3】:

      这将根据您提供的场景给出您的预期结果:

      const string = "I have a test and test and test" 
      const newString = string.replaceAll('and ', '').replaceAll(' ','-')
      console.log(newString)
      

      String.prototype.replaceAll() 来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-21
        • 1970-01-01
        • 1970-01-01
        • 2011-02-26
        • 2014-05-22
        • 2022-01-24
        • 2017-03-27
        相关资源
        最近更新 更多