I used a regex "(.*?)"
to get all the things between quotation marks in a string. After running the operations on the array provided by exec()
, I now have an array of these slices to put back into the string. How might I map this array back to the string using the regex?
I know about replacing them all with one specific value, but I'm not sure how to do it with an array. Perhaps there's some kind of map()
that takes a function that I can use to pop()
values from the array?
I'm quite new to Deno and JS in general (coming from a more low-level background), so sorry if I just missed a doc or something.
Using .replace
with a replacement function is the easiest way to accomplish what you want.
const html = `
<a href="https://example.com/foo">foo</a>
<div></div>
<a href="https://example.net/foo">foo</a>
`;
const result = html.replace(/"(.*?)"/g, (match, group) => {
return `"https://example.org/?url=${group}"`;
});
console.log(result);
You can also use a replace string with $n
replacement pattern
const html = `
<a href="https://example.com/foo">foo</a>
<div></div>
<a href="https://example.net/bar">bar</a>
`;
const result = html.replace(/"(.*?)"/g, `"https://example.org/?url=$1"`);
console.log(result);