[英]Javascript/jQuery: Replace Text in Single Quotes with HTML span tags
I have a string like this: 我有一个像这样的字符串:
This is a 'item:value' and another 'item2:value:2'.
I want to use Javascript/jQuery to get the following result: 我想使用Javascript / jQuery获得以下结果:
This is a <span class="text">item:value</span> and another <span class="text">item2:value:2</span>.
使用补充:
$("div").html('This is a <span class="text">' + item + ':' + value + '</span> and another <span class="text">' + item2 + ':' + value2 + '</span>');
Try this: 尝试这个:
<script>
var string = "This is a 'item:value' and another 'item2:value:2'.";
var res = string.split("'");
var output = res[0] + "<span class='text'>" + res[1] + "</span>" + res[2] + "<span class='text'>" + res[3] + "</span>" + res[4] ;
console.log(output);
</script>
Hope this is what you meant. 希望这就是你的意思。
You can run a regex replace()
on the text between the single quotes: 您可以在单引号之间的文本上运行正则表达式
replace()
:
var str = "This is a 'item:value' and another 'item2:value:2'."
var newString = str.replace(/'(.*?)'/g, function myFunction(x){
x = "<span class='text'>"+ x +"</span>"
return x;
})
Fiddle https://jsfiddle.net/ce1qm0za/ 小提琴https://jsfiddle.net/ce1qm0za/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.