简体   繁体   English

在关键字或角度中的特定字符后修剪字符串

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

I have this url我有这个网址

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

I want to get the string after the equal sign我想得到等号后的字符串

How to do that?怎么做?

Using lastIndexOf and substr methods of string.使用字符串的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'


Edited: multiple query parameters support编辑:多个查询参数支持

Using match method of string:使用字符串的匹配方法:

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

You can use URLSearchParams for this.您可以为此使用URLSearchParams It's a parser for query strings.它是查询字符串的解析器。

Here's how it's used:这是它的使用方法:

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')

Be aware that this is not supported on IE.请注意,这在 IE 上不受支持。 For cross-browser variations of this, you can have a look at this answer .对于跨浏览器的变体,您可以查看此答案

use split and array使用拆分和数组

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