【问题标题】:What is the regex to remove last + sign from a string从字符串中删除最后一个 + 符号的正则表达式是什么
【发布时间】:2021-03-30 07:42:49
【问题描述】:

我正在尝试使用 jQuery 生成链接,并且需要修剪最后的“+”号。有没有办法检测那里是否有一个,然后将其修剪掉?

到目前为止,代码删除了“酒店”这个词,并用“+”替换了空格,我想我只需要另一个替换“+”,有时会出现,但不确定如何超级具体。

var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");

【问题讨论】:

  • 我回答了标题。但是用例是什么。为什么你有需要摆脱的空间,它们为什么会出现?你能解释一下实际情况吗? name的内容是什么,链接应该是什么样子

标签: javascript regex


【解决方案1】:

答案

What is the regex to remove last + sign from a string

这是

const str = "Hotel+"
const re = /\+$/; // remove the last plus if present. $ is "end of string"
console.log(str.replace(re,""))

但是,问题是这是否解决了手头的实际问题

如果你有字符串

"Ritz Hotel"

你想拥有

https://www.ritz.com

然后你可以修剪字符串:

const fullName = "Ritz Hotel",
  name = fullName.replace("Hotel", "").trim().toLowerCase(),
  link = `https://www.${name}.com`;

console.log(link)

// or if you want spaces to be converted in url safe format

const fullName1 = "The Ritz Hotel",
  name1 = fullName1.replace("Hotel", "").trim().toLowerCase(),
  link1 = new URL(`https://www.hotels.com/search?${name1}`).toString()

console.log(link1)

【讨论】:

    【解决方案2】:

    作为 mplungjan 答案的替代方案,您可以使用str.endsWith() 进行检查。如果它以+ 结尾,它将被删除。不需要正则表达式。如果您可以避免使用正则表达式,那么您绝对应该这样做。

    let str = "Hotel+";
    if (str.endsWith("+")) {
      str = str.substr(0, str.length - 1);
    }
    console.log(str);

    您可以在下面找到一个将所有空白字符替换为+(不包括最后一个字符)的函数:

    const raw = "My Ho te l ";
    
    function replaceSpacesWithPlus(raw) {
      let rawArray = Array.from(raw);
      let replArray = [];
      for (let i = 0; i < rawArray.length; i++) {
        const char = rawArray[i];
        // handle characters 0 to n-1
        if (i < rawArray.length - 1) {
          if (char === ' ') {
            replArray.push('+');
          } else {
            replArray.push(char);
          }
        } else {
          // handle last char
          if (char !== ' ' && char !== '+') {
            replArray.push(char);
          }
        }
      }
      return replArray;
    }
    
    console.log(replaceSpacesWithPlus(raw));

    【讨论】:

    • 为什么要避免正则表达式?我的示例在一个语句中检测到 AND 删除
    • @mplungjan 因为正则表达式很慢,如果你想实现新特性,语法很难扩展。如果你可以使用像endsWith 这样的内置函数,它的查找速度会比正则表达式快得多。
    • 我可以想象你是否需要处理成千上万行。在这种情况下,我会捍卫我的代码是解决这个特定问题的最务实的方法。
    • @mplungjan Ikr。这一点我已经说过多次了。 :) 速度是最后需要担心的——如果正则表达式变得更复杂或有副作用,你必须再次重写整个功能。所以你可以从一开始就做。我不得不在我的工作中多次这样做。代码的可维护性和可扩展性非常重要。这才是真正的痛点。正如我所说,这是一种替代方案。
    【解决方案3】:

    下面的 sn-p 将从字符串中删除所有现有的 + 符号。

    let str = 'abcd + efg + hij';
    str = str.replace(/\+/gm, '');
    //output: abcd  efg  hij
    

    使用下面的 sn-p 进行修剪。它将删除字符串周围的空格。

    let str = "   Hello    World!!   "
    str = str.trim();
    // output: Hello    World!!
    

    如果您只想替换最后一个 + 符号。

    let str = 'abcd + efg + hij';
    let lastIndex = str.lastIndexOf('+');
    
    if (lastIndex > -1) {
        let nextString = str.split('');
        nextString.splice(lastIndex, 1, '');
        str = nextString.join('');
    }
    // output: abcd + efg  hij
    

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多