简体   繁体   English

使用Javascript查找替换URL的短部分

[英]Find Replace Short Part of URL using Javascript

Assume I have the following URL stored in variable called content : 假设我将以下URL存储在名为content变量中:

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

Problem: 问题:

  1. I need to replace watch?v= with embed/ 我需要将watch?v =替换为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: 页面源代码中的URL显示为:

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. 这里没有必要使用g标志。

Try this instead: 试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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