【问题标题】:Removing elements of string before a specific repeated character in it in javascript在javascript中删除特定重复字符之前的字符串元素
【发布时间】:2021-08-15 14:37:29
【问题描述】:

我正在尝试从我的字符串中删除特定字符之前的所有元素,该字符以这种方式重复多次:

let string = http://localhost:5000/contact-support

因此,我只是想删除第三个 / 之前的所有内容 结果是:contact_support

为此我刚刚设置:

string.substring(string.indexOf('/') + 3);

猜猜这不是正确的方法

请提供有关如何以最简单的方式改进这一点的任何帮助? 提前谢谢!!!

【问题讨论】:

    标签: javascript string split substring trim


    【解决方案1】:

    您似乎想在此处进行一些 URL 解析。 JS 带来了少数 URL 实用程序,可以帮助您完成此任务以及其他类似任务。

    const myString = 'http://localhost:5000/contact-support';
    
    const pathname = new URL(myString).pathname;
    
    console.log(pathname); // outputs: /contact-support
    
    // then you can also remove the first "/" character with `substring`
    const whatIActuallyNeed = pathname.substring(1, pathname.length);
    
    console.log(whatIActuallyNeed); // outputs: contact-support

    【讨论】:

      【解决方案2】:

      希望这会奏效

      string.split("/")[3]
      

      它将返回第三个正斜杠之后的子字符串。

      【讨论】:

      • 超级简单,超级有效。谢谢@Abir
      • 不客气..!!希望你会选择我的答案..!!
      【解决方案3】:

      你也可以使用lastIndexOf('/'),像这样:

      string.substring(string.lastIndexOf('/') + 1);
      

      另一种可能是正则表达式:

      string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
      

      注意斜线必须转义,因为它是正则表达式中的分隔符。

      【讨论】:

        【解决方案4】:

        如果您希望明确使用 indexOf 函数,string.substring(string.lastIndexOf('/')+1) 也可以完成这项工作。

        【讨论】:

          猜你喜欢
          • 2016-08-30
          • 2023-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-30
          • 2018-05-15
          • 1970-01-01
          • 2017-11-15
          相关资源
          最近更新 更多