使用正则表达式将比例因子应用于JavaScript字符串变量

使用正则表达式将比例因子应用于JavaScript字符串变量,javascript,regex,Javascript,Regex,下面有一个名为“嵌入”的字符串,我想通过比例因子(.8)修改宽度参数 scale=.8; var嵌入=“”; 因此,完成后,嵌入字符串应为: embed = '<iframe width="768" height="315" src="//www.youtube.com/embed/kk5xfJodtrk" frameborder="0" allowfullscreen></iframe>'; embed=''; 实际上,如果没有引号,width=768也适用于我

下面有一个名为“嵌入”的字符串,我想通过比例因子(.8)修改宽度参数

scale=.8;
var嵌入=“”;
因此,完成后,嵌入字符串应为:

embed = '<iframe width="768" height="315" src="//www.youtube.com/embed/kk5xfJodtrk" frameborder="0" allowfullscreen></iframe>';
embed='';
实际上,如果没有引号,width=768也适用于我

我试过很多东西。最新的是

var scale = .8;
var embed = '<iframe width="960" height="315" src="//www.youtube.com/embed/kk5xfK0ovrk" frameborder="0" allowfullscreen></iframe>';

var new_embed = embed.replace(/width="(\d+)/,"width=" + scale*$1);
var等级=.8;
var嵌入=“”;
var new_embed=embed.replace(/width=“(\d+)/,“width=“+scale*$1);
但这抱怨说$1没有定义

谢谢你的帮助。

//位长,但有效,可以缩短,无需时间:P
var标度=0.5;
var嵌入=“”;
var embed=embed.replace(/width=“(\d+)/,function myFunction(x){return”width=\”“+x.replace(“width=\”“,”“)*scale;});
var embed=embed.replace(/height=“(\d+)/,function myFunction(y){return”height=\”“+y.replace(“height=\”“,”“)*scale;});

document.write(嵌入);
不要使用正则表达式:

// create temporary element and parse HTML inside
var d = document.createElement('div');
d.innerHTML = embed;

// adjust width
d.firstChild.width *= 0.8;

// write into the document (or use appendChild)
document.write(d.innerHTML);

你不能这样做,$1是正则表达式引擎中的一个子字符串,你需要使用一个特殊的匿名函数。试试这个
/width=“?(\d+)”/gi
演示。谢谢!对我有用的是:var embed=embed.replace(/width=“(\d+)/,function(x,y){return width=\'+scale*y});
// create temporary element and parse HTML inside
var d = document.createElement('div');
d.innerHTML = embed;

// adjust width
d.firstChild.width *= 0.8;

// write into the document (or use appendChild)
document.write(d.innerHTML);