简体   繁体   中英

Find Replace Short Part of URL using Javascript

Assume I have the following URL stored in variable called content :

http://www.example.com/watch?v=4444444&feature=related

Problem:

  1. I need to replace watch?v= with embed/
  2. I need to erase whatever comes after &

The final output would look like:

http://www.example.com/embed/4444444

I tried these two steps but didn't work:

content = content.replace('/watch?v=/', 'embed/');
content = content.replace('&*/g','');

The URL in page source code appears as:

http://www.example.com/watch?v=4444444&feature=related

You have many errors:

  • You are using a regular expression when you only need a string.
  • You are writing your regular expressions as strings.
  • To write 'match any characters' you need to write '.*' , not just '*' . The star modifies the previous token.
  • There is no need to use the g flag here.

Try this instead:

 content = content.replace('watch?v=', 'embed/').replace(/&.*/, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM