需要将字符串数据中的所有超链接更改为其他值
Need to change all the hyperlinks in string data to another value
我有一个字符串中的链接列表。
var data='<ol>
<li><a href="#/getpage/getData/1">A Christmas Carol</a></li>
<li><a href="#/getpage/getData/2">Copyright</a></li>
</ol>'
需要使用javascript或jquery将字符串中的所有链接更改为以下格式。
data = '<ol>
<li><a href="getCurrentPage(1)">A Christmas Carol</a></li>
<li><a href="getCurrentPage(2)">Copyright</a></li>
</ol>'
有人能在这方面帮我吗。提前谢谢。
尝试:
var data='<ol><li><a href="#/getpage/getData/1">A Christmas Carol</a></li><li><a href="#/getpage/getData/2">Copyright</a></li></ol>'
var el = $("<div>"+ data + "</div>");
el.find('li').each(function(i) {
$(this).find('a').attr('href' , "getCurrentPage("+(i+1)+")");
});
data = el.html();
alert(data);
样品Fiddle
对于未排序的字符串;
var data='<ol><li><a href="#/getpage/getData/1">A Christmas Carol</a></li><li><a href="#/getpage/getData/2">Copyright</a></li></ol>'
var el = $("<div>"+ data + "</div>");
el.find('li').each(function(i) {
var num = $(this).find('a').attr('href').replace('#/getpage/getData/','');
$(this).find('a').attr('href' , "getCurrentPage("+ num +")");
});
alert(el.html());
嗨,您可以使用以下脚本。
$("a").each(function(){
var href=$(this).attr("href");
$(this).attr("href","getCurrentPage("+href.substring(href.lenght-1,href.length)+")");
});
也许你可以试试:
// use Regex to reformat the data
var myregex = new RegExp('<a href="#/getpage/getData/([0-9]+)">', 'g'); // g means "global", i.e. match all
var formated_data = data.replace(myregex, '<a href="getCurrentPage($1)">') // $1 is replaced by the content of the 1st parenthetis of the regex
这将在"#/getpage/getData/"+任何整数的形式下找到所有带有href的"a"标记,并将其替换为"getCurrentPage("+上面的整数+"("形式下带有href的"a"标记。您也可以只匹配href,而不需要计算"a"标记。
$('a[href^="#/getpage/getData/"]').each(function(){
var href = $(this).attr("href");
var id = href.replace('#/getpage/getData/','');
$(this).attr('href', 'getCurrentPage(' + id + ')');
});
你可以在这里试试。
我觉得您已经找到了解决方案。只是我花了一些时间在这方面,我想分享我的解决方案。如果你不同意我的解决方案,我不会介意的。如果您能看看解决方案,我将不胜感激。
这是小提琴。http://jsfiddle.net/ardeezstyle/ARPzA/
$('body').append('<div/>').find('div:last').addClass('temp');
$('.temp').html(data);
$('.temp a[href^="#/getpage/getData/"]').each(function(){
var href = $(this).attr("href");
var id = href.replace('#/getpage/getData/','');
$(this).attr('href', 'getCurrentPage(' + id + ')');
});
data=$('.temp').html();
$('.temp').text(data);
干杯!
使用javascript的replace函数,http://www.w3schools.com/jsref/jsref_replace.asp
相关文章:
- 制作一个不带HTML a标记但在动画播放完毕后指向其他页面的超链接
- 单击超链接时,如何使用Google Maps API v3缩放地图
- 用超链接替换URLS
- 使用JavaScript从超链接加载时的默认下拉值
- Hammer.js阻止在Android Webview中点击超链接
- 将超链接添加到“;标题“;标记文本
- 文本建议的超链接
- 用Javascript按钮替换Javascript超链接
- 删除默认的ui超链接行为
- 谷歌将广告超链接映射到国家标记
- 如何在点击超链接时调用fullcalendar回调
- 单击“禁用其他超链接”
- 为Angularjs制作超链接
- 指向的超链接刚刚赢得'不起作用
- 如何将超链接添加到通过传单创建的传单多段线.Draw
- 如何禁用鼠标中键单击超链接以在新选项卡或新窗口中打开
- 通过超链接传递到其他页面的数据正在被切断
- 使用js或jquery将超链接更改为其他内容
- 目标特定标签与超链接从其他页面在同一网站
- 需要将字符串数据中的所有超链接更改为其他值