【发布时间】:2021-04-01 17:02:04
【问题描述】:
我是 JavaScript 新手。我在<p> 标签中有 3 个 10 位数字,我想选择它们并将它们转换为链接。我能够获得数字并将它们转换为链接,但是我同时获得了所有 3 个数字和一个链接,如果我能得到一些帮助,那就太好了,谢谢
这是我的代码:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '<a href= "'+link+'">"'+text+'"</a>');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>
【问题讨论】:
-
我在
标签中有 3 个 10 位数字的数字 <p> element。 HTML 只有一种数据类型:
string。如果您需要在 JavaScript 中将字符串视为数字,则需要对其进行转换。 -
你说得对,它们是字符串。我只想获取字符串,但仅将其中一个字符串显示为链接,而不是所有匹配的字符串。
标签: javascript arrays regex function dom