Jquery replace url with params?

HI guys I can’t seem to find a way to find this sertain url in content and replace it. All works when URL does not contain parameters but can not make it work otherwise.

Find and repace this: **https://www.youtube.com/watch?v=hMZ0Q7Yio8g&list=RDhMZ0Q7Yio8g&start_radio=1**

in this string:

**hello this is a test string replace me https://www.youtube.com/watch?v=hMZ0Q7Yio8g&list=RDhMZ0Q7Yio8g&start_radio=1 content continues!**

I have tried this:

**let regex = '/https://www.youtube.com/watch?v=hMZ0Q7Yio8g&list=RDhMZ0Q7Yio8g&start_radio=1/g';**

**str.replace(regex, "red");**

but does not work.

Please help.

Well the Syntax highlighter is going to start you off first of all.

/ is your delimiter. So it can’t appear in the string. But it does. 3 times.

You need to escape the forward slashes in the middle of the string with backslashes. \/

Secondly, inline regexes in javascript dont have quotes around them. What you’ve done there is told your code to find a literal string /https://www.youtube.com/watch?v=hMZ0Q7Yio8g&list=RDhMZ0Q7Yio8g&start_radio=1/g

Thirdly… if you’re finding exactly that string, you dont need a regex unless it will appear more than once. (Or… yaknow… replaceAll?)

EDIT: Woops. Knew i’d miss at least one… Fourthly, the . and ?s are special characters in regexes, so you’ll need to escape that too.

1 Like

You might find regex101.com useful for testing your regexes out. It tends to be my go to.

As m_hutley has pointed out if it is an exact match then there is no need for a regex.

That said here is a link which follows m_hutley’s advice using the necessary escapes.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.