Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

map array of parts to string via regex in deno (typescript)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading