【问题标题】:trim string after keyword or a specific character in angular在关键字或角度中的特定字符之后修剪字符串
【发布时间】:2018-03-07 01:41:43
【问题描述】:

我有这个网址

/application-form?targetDate=2018-03-21

我想得到等号后面的字符串

怎么做?

【问题讨论】:

    标签: javascript string angular url trim


    【解决方案1】:

    使用lastIndexOfsubstr字符串方法。

    const url = '/application-form?targetDate=2018-03-21';
    
    const lastEqualSignIndex = url.lastIndexOf('=');
    const datePart = url.substr(lastEqualSignIndex + 1);
    
    console.log(datePart); // -> '2018-03-21'

    编辑:支持多个查询参数

    使用match字符串方法:

    const [, targetDateValue] = '/application-form?targetDate=2018-03-21'.match(/[\?&]targetDate=([^&#]*)/);
    
    console.log(targetDateValue); // -> '2018-03-21'

    【讨论】:

    • OP 应该记住,这不支持多个查询参数。它总是会得到最后一个查询参数的值。
    • 是的。以前的解决方案是针对问题中的特定情况。我们还可以在正则表达式中包含查询参数名称,以便在有多个查询参数时仅匹配其对应的值。例如:'/application-form?targetDate=2018-03-21'.match(/[\?&]targetDate=([^&#]*)/)[1]
    【解决方案2】:

    您可以为此使用URLSearchParams。它是查询字符串的解析器。

    它的使用方法如下:

    new URLSearchParams('?targetDate=2018-03-21').get('targetDate') 
    
    // or if you want to use your URL as-is:
    new URLSearchParams('/application-form?targetDate=2018-03-21'.split('?')[1]).get('targetDate')
    

    请注意,IE 不支持此功能。对于这个的跨浏览器变体,你可以看看这个answer

    【讨论】:

      【解决方案3】:

      使用拆分和数组

      var param = "/application-form?targetDate=2018-03-21";
      var items = param.split("=");
      var arr1 = items[0];
      var arr2 = items[1];
      var result = arr2;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        相关资源
        最近更新 更多