简体   繁体   中英

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.

 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. 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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM