JS:
function test() {
var str = "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"312\" height=\"312\" />";
str += "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"412\" height=\"412\" />";
str = str.replace(/ height="\d+"/g, " height=\"90\"");// “/”后面的是要替换的字符,“d\+”是数字,最后""里是用来填充的字符
str = str.replace(/ width="\d+"/g, " width=\"90\"");
alert(str);
}<input type="button" id="hh" onclick="test();" value="hell" />
C#:
var str = "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"312\" height=\"312\" />";
str += "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"412\" height=\"412\" />";
Regex reg = new Regex("width\\s*=\\s*\\S+ height\\s*=\\s*\\S+");
string result = reg.Replace(str, "width=\"90\" height=\"90\"");
第二种方法替换
//Regex reg1 = new Regex("height\\s*=\\s*\\S+");
//string result1 = reg1.Replace(result, "height=\"90\"");
处理多张图片中出现没有width height的情况:
//正则替换图片的宽高
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(item.AdImg);
var relImg = string.Empty;
foreach (Match m in matches)
{
//进行匹配img是否存在width height
Regex reg = new Regex("width\\s*=\\s*\\S+ height\\s*=\\s*\\S+");
if (!reg.IsMatch(m.Value))//img 中不存在width height
{
//获取其他属性进行替换
Regex reg1 = new Regex("alt\\s*=\\s*\\S+");
relImg += reg1.Replace(m.Value, "style=\"width:90px;height:90px;\"");
}
else
{
relImg+= reg.Replace(m.Value, "style=\"width:90px;height:90px;\"");
}
}

本文介绍了一种使用JavaScript和C#来统一HTML中所有图片尺寸的方法。通过正则表达式替换图片的宽度和高度属性,确保所有图片显示为统一大小。特别针对图片标签中可能缺失width和height属性的情况进行了处理。
4320

被折叠的 条评论
为什么被折叠?



