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

How to replace part of a string in JavaScript regex?

I have the following string https://firebasestorage.googleapis.com/v0/b/redapp-2fc9e.appspot.com/o/users/itAgSBwfmEbNrHvWUQzh02/profilePhoto/38368-6535-4f88-bcc2-2eecdeb3d38c.jpg?alt=media&token=aa20c34f-dcdf-4419-b664-50608b, I need to apply encodeURIComponent() to a part of the string such that the final string becomes like this: https://firebasestorage.googleapis.com/v0/b/redapp-2fc9e.appspot.com/o/users%2itAgSBwfmEbNrHvWUQzh02%2profilePhoto%238368-6535-4f88-bcc2-2eecdeb3d38c.jpg?alt=media&token=aa20c34f-dcdf-4419-b664-50608b. How can I do so?

I have the following regex /(users.+)\?/i but it matches 2 groups.

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 :

Try using this

const str = 'https://firebasestorage.googleapis.com/v0/b/redapp-2fc9e.appspot.com/o/users/itAgSBwfmEbNrHvWUQzh02/profilePhoto/38368-6535-4f88-bcc2-2eecdeb3d38c.jpg?alt=media&token=aa20c34f-dcdf-4419-b664-50608b, I need to apply encodeURIComponent()';
const groups = str.match(/(user.*?)\?/i);
console.log(groups[1]);

/(user.*?)\?/i looks for the word user followed by any character until it encounters ‘?’. The ‘?’ is a regex token so needs to be escaped. And finally the ‘?’ in user.*? makes the regex to lazy match.
Also just because the length of groups returned is 2 doesn’t mean there were 2 matches. Groups start at index 1, so 1st matched grouped will be at index 1.

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