I need to access the value in a string between 2 words.
In my string I have 2 words : entityID=
and =menu
. Between those 2 words I have an number which can be in single character like 1-9 or two or more characters.
I want to tell to javascript, find me the characters between 'entityId=' and '=menu'.
[EDIT]
I tried with this function but no success :
function getId(str, start, end) {
const result = str.match(new RegExp(start "(.*)" end));
return result[1];
}
getId(myString, 'entityId= ', '&menu')
but I got an errror
Any idea ?
CodePudding user response:
What the question was about
If you are sure that the entityId=
and the &menu=
key are provided, you can use the method split to retrieve your string as the following example
const string = "http://myAmazingUrl?entityId=100101010&menu=1"
const word = string.split("entityId=")[1].split("&menu")[0]
console.log(word)
A little more
Here, it seems that you are trying to retrieve the key of a request.
I would suggest you to use the Url object and retrieve your parameters using searchParams
const url = new URL("http://myAmazingUrl?entityId=100101010&menu=1");
const entityId = url.searchParams.get("entityId");
console.log(entityId);
CodePudding user response:
This function should help.
function getStringInBetween(str, start, end) {
const res = str.match(new RegExp(start "(.*)" end));
return res[1];
}
const string = 'Hello my Stack Overflow friends';
console.log(getStringInBetween(string, 'Hello ', ' Stack'));
-- Output --
my