[英]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
我有一个p tag
,我想在a tag
包装一个单词
Lorem ipsum @dolor sit amet, consectetur to Lorem ipsum @dolor坐在amet, 对
Lorem ipsum @dolor sit amet, consectetur Lorem ipsum @dolor坐在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. 这里(@.*?)
是捕获组, $1
将具有整个匹配字符串中的捕获字符串。
Since You are using jQuery anyways try this 由于您无论如何都使用jQuery,请尝试此操作
$("p").each(function(){
$(this).replaceWith($(this).html().replace(/(@[^\s]+)/,"<a href='#'>$1</a>"))
})
Good 'ol fashioned looping: 好的'ol老式循环:
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(' ');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.