Skip to content Skip to sidebar Skip to footer

How To Extract Href Attribute From Link And Create A Specific Pattern Of That?

I explain my question with two examples: Example1: current string: var str = 'anything untitled anything'; //

Solution 1:

I don't understand. What you have done is right. Here are your solutions working perfectly fine:

$(function () {
  var str = 'anything <a href="www.google.com" target="_blank">untitled</a> anything';
  var newStr = $('<div/>', {html: str}).find("a").replaceWith(function(){
    return ($(this).text().trim().toLowerCase() == 'untitled') ? $(this).attr('href') : "[" + $(this).text() + "](" + $(this).attr('href') + ")";
  }).end().text();
  $("body").append(newStr + "<br /><br />");
  str = 'anything <a href="www.google.com" target="_blank">any thing else</a> anything';
  newStr = $('<div/>', {html: str}).find("a").replaceWith(function(){
    return ($(this).text().trim().toLowerCase() == 'untitled') ? $(this).attr('href') : "[" + $(this).text() + "](" + $(this).attr('href') + ")";
  }).end().text();
  $("body").append(newStr);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Updated Code (better version)

$(function () {
  var str = 'anything <a href="www.google.com" target="_blank">untitled</a> anything';
  var newStr = string_it(str);
  $("body").append(newStr + "<br /><br />");
  str = 'anything <a href="www.google.com" target="_blank">any thing else</a> anything';
  newStr = string_it(str);
  $("body").append(newStr);
});

functionstring_it (str) {
  return $('<div/>', {html: str}).find("a").replaceWith(function(){
    return ($(this).text().trim().toLowerCase() == 'untitled') ? $(this).attr('href') : "[" + $(this).text() + "](" + $(this).attr('href') + ")";
  }).end().text();
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Post a Comment for "How To Extract Href Attribute From Link And Create A Specific Pattern Of That?"