【问题标题】:Using regex to remove characters till the last -使用正则表达式删除字符直到最后 -
【发布时间】:2021-07-08 11:10:29
【问题描述】:

我是正则表达式的新手,并试图弄清楚如何删除字符串中的最后一个字符。我目前的字符串格式如下:

purple-hoodie.jpg-1625739747918

我正在尝试删除基本上留下的字符:

-1625739747918

有人对如何解决这个问题有任何建议吗?我正在努力弄清楚如何指示到达字符串中的最后一个 - 如果可能的话?

谢谢

【问题讨论】:

  • 不是反应问题
  • 如果您找到了问题的答案,请不要忘记接受它(绿色勾号)!
  • @Apostolos 感谢您的提醒!

标签: javascript regex string


【解决方案1】:

只需使用lastIndexOf

let str = 'purple-hoodie.jpg-1625739747918'
console.log(str.substring(str.lastIndexOf('-')))

【讨论】:

    【解决方案2】:

    我更喜欢match 方法:

    var input = "purple-hoodie.jpg-1625739747918";
    var output = input.match(/-\d+$/)[0];
    console.log("match is: " + output);

    但这假设输入将以所有数字结尾。更通用的正则表达式方法可能会使用全部替换:

    var input = "purple-hoodie.jpg-1625739747918";
    var output = input.replace(/^.*(?=-)/, "");
    console.log("match is: " + output);

    【讨论】:

      【解决方案3】:

      这是我的解决方案。

      const txt = 'purple-hoodie.jpg-1625739747918';
      const result = txt.replace(/-\d+$/, '');
      console.log(result)
      

      这会删除以 - 为前缀的最后一个尾随数字。

      【讨论】:

      • 这会删除 OP 想要匹配的内容,留下不需要的内容。
      • @Tim 请举个例子
      猜你喜欢
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2019-03-21
      • 1970-01-01
      • 2022-07-26
      • 2020-08-24
      • 2023-02-02
      相关资源
      最近更新 更多