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.
>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.