簡體   English   中英

在關鍵字或角度中的特定字符后修剪字符串

[英]trim string after keyword or a specific character in angular

我有這個網址

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

我想得到等號后的字符串

怎么做?

使用字符串的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'


編輯:多個查詢參數支持

使用字符串的匹配方法:

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

您可以為此使用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 上不受支持。 對於跨瀏覽器的變體,您可以查看此答案

使用拆分和數組

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM