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

JS Replace text in between unique expression in parentheses (i)

My intention is to build a parsing function which searches within a string (think blog post) for any substrings wrapped around unique identifiers in parentheses, like (i).

My current implementation isnt working. Would truly appreciate any help!

let text = "Hello there (i)Sir(i)";
let italics = /\(i\)(.?*)\(i\)/gi;
let italicsText = text.match(italics);
// text.replace(italics, <i>)

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 :

You can use replace here with regex as:

\((.*?)\)/g

Second argument to replace is a replacer function.

replace(regexp, replacerFunction)

A function to be invoked to create the new substring to be used to
replace the matches to the given regexp or substr.

How arguments are passed to replacer function

let text = 'Hello there (i)Sir(i)';
let italics = text.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics);

let text2 = 'Hello there (test)Sir(test)';
let italics2 = text2.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics2);
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