Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

js正则表达式如何将span标签替换为img标签,并将原span标签的内容放到img标签的src中

需求如下:

需要将字符串通过正则表达式

var str = "<h2>11</h2><span>http://files.cnblogs.com/files/wj204/2.gif</span><h2>22</h2><p>33</p><span>http://files.cnblogs.com/files/wj204/ali.gif</span>";

转化为:

var str = "<h2>11</h2>
<img src ="http://files.cnblogs.com/files/wj204/2.gif" / >
<h2>22</h2><p>33</p>
<img src="http://files.cnblogs.com/files/wj204/ali.gif"/>";

这样的结果

目前我做到的是:

1.把span标签内容匹配出来,代码为:

str.match(/<span>(.*?)</span>/g)

结果为:
图片描述

2.用replace将span标签替换为img标签

str.replace(/<span>(.*?)</span>/g, "<img src/>")

结果:图片描述

接下来要怎么处理?如何将这两步关联起来,得到我的预期结果。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
str.replace(/<span>(.*?)</span>/g, '<img src="$1"/>')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...