gpt4 book ai didi

javascript - Coffeescript:替换 src 属性

转载 作者:行者123 更新时间:2023-11-30 21:20:37 25 4
gpt4 key购买 nike

我是 CoffeeScript 的新手,我的最终目标是将图像标签中 src 的值更改为不同的值。 输入将是一个字符串。

让我们说

string  x = '<div class="sample">
<img src="/i/java.png">
</div>
<div class="sample">
<img src="/i/python.png">
</div>'

我想将 src 的内容替换为其他内容。我尝试使用正则表达式进行尝试,但它不起作用。关于如何实现这一目标的任何想法。我使用了这个正则表达式。

 s.replace /[/"][//]{1}i[//]{1}/g, '"//cdn.example.com/' 

我正在使用我的本地应用程序以及 this测试我的代码的网站

最佳答案

我认为您的原始正则表达式有问题。

试试这个例子,

x = '<div class="sample">
<img src="/i/java.png">
</div>
<div class="sample">
<img src="/i/python.png">
</div>'

console.log(x.replace /\/i\/[a-zA-Z1-9]+.png/g, '"//cdn.example.com/')

正则表达式 /\/i\/[a-zA-Z1-9]+.png/g 应该匹配格式为 /i/anything_here.png< 的任何值,但要确保 anything_here 值至少包含 1 个字符(因此 /i/.png 不会匹配)。


如果您的字符串在 .png 文件名之前可能包含更多子路径,请使用以下正则表达式 - \/i(\/[a-zA-Z1-9]+)+。 png

此正则表达式将允许在 /filename.png 之前出现尽可能多的 /anything

关于javascript - Coffeescript:替换 <img> src 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com