Reputation: 39
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>")
}
})
})
Upvotes: 0
Views: 59
Reputation: 18987
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.
Upvotes: 0
Reputation: 3375
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(' ');
});
Upvotes: 0
Reputation: 1528
Since You are using jQuery anyways try this
$("p").each(function(){
$(this).replaceWith($(this).html().replace(/(@[^\s]+)/,"<a href='#'>$1</a>"))
})
Upvotes: 0