如何用正则表达式替换2斜杠之间的文本?

时间:2017-03-09 23:11:02

标签: javascript regex

我有一个src属性,我只想替换b1//imglibrary之间的任何维度: b1/200x300/imglibrary

<img class="Img" src="b1/200x300/imglibrary" alt=""/>
var $image = $('.Img').attr('src');
var editedImage = $image.replace(/b1\/.*?\/imglibrary/,"b1/800x600/imglibrary");
console.log(editedImage);

但输出是: /imglibrary/b1/800x600/imglibrary/

我无法简单地找到并替换文本200x300,因为该文本会根据图像而改变。任何人都可以对我出错的地方有所了解吗?

1 个答案:

答案 0 :(得分:2)

假设您想要替换分辨率值,哪个模式看起来像numberxnumber,请使用以下RegExp

var $image = $('.Img').attr('src');
var editedImage = $image.replace(/(?!\/)\d+x\d+(?=\/)/, "800x600");
console.log(editedImage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="Img" src="b1/200x300/imglibrary" alt=""/>