正则,用了问号依旧贪婪匹配问题

发布于 2022-09-07 11:53:50 字数 1185 浏览 9 评论 0

var str='第一个视频<iframe frameborder="0" width="640" height="498" src="https://v.qq.com/iframe/player.html?vid=a0678a3ahqx&tiny=0&auto=0" allowfullscreen=""></iframe>第二个视频<iframe frameborder="0" width="640" height="498" src="https://v.qq.com/iframe/player.html?vid=a0678a3ahqx&tiny=0&auto=0" allowfullscreen=""></iframe>没有了'
var result=str.replace(/(<iframe) (.*) (width=\".*?\") (height=\".*?\") (.*)(<.*?iframe>)/g,"$1 $2 width='100%' $5 $6")
console.log(result)

我想把iframe里的width="640" height="498"用正则替换为width="100%"
于是就写上上述正则,发现如果字符串里只有一个iframe是成功替换的,但是如果有2个iframe的话,就只会替换第2个iframe了.
求大神帮助,希望每个iframe里,width="640" height="498"变成width="100%"
图片描述
在线调试地址http://jsbin.com/dumuxewubu/e...

=============分割线,问题解决啦======================================
发现之前用的非贪婪匹配方法加错了,不该用(.*)? 把问号写在括号外,
用了这个就好了

var result=str.replace(/(<iframe) (.*?) (width=\".*?\") (height=\".*?\") (.*?)(<.*?iframe>)/g,"$1 $2 width='100%' $5 $6")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九命猫 2022-09-14 11:53:50

解决啦,发现之前用的非贪婪匹配方法加错了,不该用(.*)? 把问号写在括号外,
用了这个就好了

解决啦,发现之前用的非贪婪匹配方法加错了,不该用(.*)? 把问号写在括号外,
用了这个就好了
var result=str.replace(/(<iframe) (.*?) (width=\".*?\") (height=\".*?\") (.*?)(<.*?iframe>)/g,"$1 $2 width='100%' $5 $6")
羁绊已千年 2022-09-14 11:53:50

如果没有性能要求的话(但和用jquery插入再改相比肯定快得多),可以用cheerio,就不用跟正则搞来搞去了(而且很安全)

import cheerio from 'cheerio';
var str='第一个视频<iframe frameborder="0" width="640" height="498" src="https://v.qq.com/iframe/player.html?vid=a0678a3ahqx&tiny=0&auto=0" allowfullscreen=""></iframe>第二个视频<iframe frameborder="0" width="640" height="498" src="https://v.qq.com/iframe/player.html?vid=a0678a3ahqx&tiny=0&auto=0" allowfullscreen=""></iframe>没有了'
var $ = cheerio.load(str, {decodeEntities: false});
$('iframe').attr('width','100%')
console.log($.html())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文