How do I get content inside two strings?
Example:
Main string:
document.cookie="cookie=name";
How do I select the cookie=name part?
I tried this:
document.cookie=\"(.*?)\";
But this select the hole string not the cookie=name.
How do I get content inside two strings?
Example:
Main string:
document.cookie="cookie=name";
How do I select the cookie=name part?
I tried this:
document.cookie=\"(.*?)\";
But this select the hole string not the cookie=name.
You can use split
:
str.split('"')[1]
You have it, just extract the first match
var regex = /document.cookie=\"(.*?)\";/;
var match = regex.exec('document.cookie="cookie=name";');
console.log(match[1]);
let str = 'document.cookie="cookie=name"';
let regx = /\".+=.+\"$/;
let match = str.match(regx)[0].replace(/\"/g, "");
console.log(match);
let [data, name] = match.split("=");
console.log("Data: " + data + " and name: " + name);
While splitting the string on a double quote is certainly efficient, the OP composed the post in a way that expresses interest in using a regex, a point this answer addresses. You may isolate the portion you wish to extract from the outer string with a regex that matches a pattern located at the end of str
. Next, the string uses its replace method to globally replace all its double quotes. Then, the overall result is assigned to variable match
, At this point, one now has extracted the inner string 'cookie=name'.
Of course, you may manipulate match
by splitting its string value on the equals character as this code does in a statement that employs array destructuring. This action results in variables data
and name
respectively containing the values "cookie" and "name".