简体   繁体   中英

How can i wrap a word from a p in an a tag

I have a p tag and I want to wrap a word in an a tag

Lorem ipsum @dolor sit amet, consectetur to
Lorem ipsum @dolor sit amet, consectetur

I've tried this:

objectP = document.getElementsByTagName('p');
$.each(objectP, function(i, val){

    arrayWords = val.innerHTML.split(" ")

    $.each(arrayWords, function(i, val){

        if(val[0] === '@'){

            val.wrap("<a></a>")

        }

    })

})

You can use regex with capturing group to make things simpler

objectP = document.getElementsByTagName('p');

$.each(objectP, function(i, val){
    val.innerHTML = val.innerHTML.replace(/(@.*?)\s/g, "<a href='#'>$1</a>");
})

Here (@.*?) is the capturing group and $1 will have the captured string from the entire matched string.

Since You are using jQuery anyways try this

$("p").each(function(){
  $(this).replaceWith($(this).html().replace(/(@[^\s]+)/,"<a href='#'>$1</a>"))
})

Good 'ol fashioned looping:

  var paragraphs = document.querySelectorAll('p');

  [].map.call(paragraphs, function(p) {
    var htmlArray = p.innerHTML.split(' ');

    htmlArray.map(function(word, i, arr) {
      if(word === '@dolor') {
        var a = '<a href="#">' + word + '</a>';
        arr[i] = a;
      }
    });

    p.innerHTML = htmlArray.join(' ');
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM