i have a url search key like that: ?retailerKey=A and i want to grab the retailerKey substring. All examples that i saw are having as example how to take before the char with the indexOf example. How can i implement this to have this substring from the string ?retailerKey=A
CodePudding user response:
use regex expression.
Following will return the value between character ?
and =
var result = "?retailerKey=A".match(/\?(.*)\=/).pop();
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
If you would like to always get the string between your query sign and equal sign ?ThisString=
then you can simply use indexOf for example
str.slice(str.indexOf('?') 1,str.indexOf('='))
CodePudding user response:
Using library could be a better choice but to do it from scratch : I suggest to use split with a regular expression.
// split for char equals to ? or & or =;
const url = '/toto?titi=1&tata=2';
const args = url.split(/[\?\&\=]/);
// shift the first element of the list since it the base url before "?"
args.shift();
// detect malformed url
if (args.length % 2) {
console.error('malformed url', args);
}
const dictArgs = {};
for (let i = 0; i < args.length /2; i ) {
const key = args[2*i];
const val = args[2*i 1];
dictArgs[key] = val;
}
console.log(dictArgs);
CodePudding user response:
You could split()
the string on any ?
or =
and take the middle item ([1]
) from the outcome array.
const data = "?retailerKey=A";
const result = data.split(/[\?=]/)[1];
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>