【问题标题】:javascript regex replace function removes other contentjavascript 正则表达式替换功能删除其他内容
【发布时间】:2018-03-29 14:41:49
【问题描述】:

我有一个内容(字符串),在某些部分包含完整的 youtube 网址,而在其他部分包含视频 ID。 我只需要用视频 ID 替换完整的 youtube 网址。 例如 var "content"。

var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="https://youtu.be/DluFA_AUjV8"}';

var myRegex = /{GENERICO:type="youtube",id=".*?(?:youtube\.com|youtu\.be)\/(?:embed\/|watch\?v\=)?([^\&\?\/\"]+).*?["&\?]}/gi;

content = content.replace(myRegex, '{GENERICO:type="youtube",id="$1"}' );

console.log(content);

我想要达到的结果(在示例中)是:

{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="DluFA_AUjV8"}

我实际得到的是以下内容:

the result I want to achieve (in the example) is:

{GENERICO:type="youtube",id="DluFA_AUjV8"}

由于某种原因,它删除了内容中的一个字符串。 我不知道是javascript问题还是正则表达式问题,或者我做错了什么。

这里是jsfiddle

【问题讨论】:

标签: javascript regex


【解决方案1】:

使用content.replace(new RegExp('https://youtu.be/','g'), '') 进行全局替换。

var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="https://youtu.be/DluFA_AUjV8"}';

console.log(content.replace(new RegExp('https://youtu.be/','g'), ''))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多