需要将字符串数据中的所有超链接更改为其他值

Need to change all the hyperlinks in string data to another value

本文关键字:超链接 其他 字符串 数据      更新时间:2023-09-26

我有一个字符串中的链接列表。

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