-2

I have this url

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

I want to get the string after the equal sign

How to do that?

3 Answers3

1

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'
Carloluis
  • 4,205
  • 1
  • 20
  • 25
  • OP should keep in mind that this doesn't support multiple query parameters. It will always get the value of the last query parameter. – nicholaswmin Mar 07 '18 at 01:51
  • Yes. Previous solution was targeting the particular case in the question. We can also include the query parameter name in a regex to match only it's corresponding value when there are multiple query parameters. E.g.: `'/application-form?targetDate=2018-03-21'.match(/[\?&]targetDate=([^]*)/)[1]` – Carloluis Mar 07 '18 at 02:09
1

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;
Triet Pham
  • 88
  • 1
  • 14
0

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.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167