Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用RegExp替换图像源,其中另一个属性位于第一位_Javascript_Html_Regex_Replace_Tags - Fatal编程技术网

Javascript 使用RegExp替换图像源,其中另一个属性位于第一位

Javascript 使用RegExp替换图像源,其中另一个属性位于第一位,javascript,html,regex,replace,tags,Javascript,Html,Regex,Replace,Tags,我就拿这个为例 <img style="height:375; width:500;" src="../img/ris1_1.jpg" ALIGN="center"> <img src="img/ris1_2.jpg" style="height:375; width:500;" ALIGN="center"> 如果在img以外的任何元素中未使用src属性,则使用捕获搜索字符串(并用\1启动替换字符串)来保留中的所有内容,而不是仅使用搜索字符串选择img元素的src属性

我就拿这个为例

<img style="height:375; width:500;" src="../img/ris1_1.jpg" ALIGN="center">
<img src="img/ris1_2.jpg" style="height:375; width:500;" ALIGN="center">

如果在img以外的任何元素中未使用src属性,则使用捕获搜索字符串
(并用
\1
启动替换字符串)来保留
中的所有内容,而不是仅使用搜索字符串选择img元素的src属性值


Tony的建议也是很好的。通过搜索
(并使用as replace string
\1\3\2
,可以通过将src属性移动到
之后的第一个位置,首先标准化所有img元素,如果
标记
是您的标记,您可以执行以下操作:

tag.replace(/(img[^>]*src=['"])+(\s*)[^'"]*/g, '$1REPLACED.jpg');
更新


若要省略绝对URL,请使用此正则表达式
(img[^>]*src=[''”)+(?!http:\/\/)\s*[^']*

不使用正则表达式,为什么不选择元素并更新其
.src
属性在第一个元素的img标记后移动src属性?我不能用.src替换src,因为我在文本中搜索它,从页面解析。我也不能移动src属性。(?JS regex支持lookbehinds?这是一个很好的解决方案!以及如何只替换相对路径?谢谢!它正在工作!:)但是我仍然不能添加旧的src,例如“img/ris1.jpg”来替换…不客气!另外,如果您只是在切换域,您可能需要注意相对路径中的
。/
tag.replace(/(img[^>]*src=['"])+(?!http:\/\/)\s*([^'"]*)/gi,"$1http://mydomain.com/$2");
tag.replace(/(img[^>]*src=['"])+(\s*)[^'"]*/g, '$1REPLACED.jpg');