简体   繁体   English

从字符串中提取数字并将它们包装在 HTML 中

[英]Extract numbers from string and wrap them in HTML

My requirement is as follows.我的要求如下。 I have this example text:我有这个示例文本:

html html

9216143567 is the number and other one is 0112388908

Now I want a JS function which finds then numbers which are together and greater than 8 in number and adds html code around them like below现在我想要一个 JS 函数,它可以找到一起并且大于 8 的数字,并在它们周围添加 html 代码,如下所示

<a href="tel:9216143567" class="button button-positive">9216143567</a> is the number and other one is <a href="tel:0112388908" class="button button-positive">0112388908</a>

What is the right way to do this?这样做的正确方法是什么?

Try this.尝试这个。 Takes string as input and gives HTML as output.将字符串作为输入并给出 HTML 作为输出。

 var abc = 'ei32eoeiq 9216143567 is the number and other one is 0112388908, 7878787878,deewodiwqodiwp 9898903232'; var splitArray = abc.match(/\\d+/g); for(var i = 0 ; i < splitArray.length; i++){ value = splitArray[i]; if(value.length>8) { abc = abc.replace(value, '<a href="tel:'+value+'" class="button button-positive">'+value+'</a>'); } } console.log(abc); document.getElementById("ans").innerHTML = abc;
 <div id="ans"></div>

This can be solved with a regex : (\\d{8,})[^\\d]+(\\d{8,})/g这可以用正则表达式解决: (\\d{8,})[^\\d]+(\\d{8,})/g

It matches two matching groups, each of them wraps a number of at least 8 digits;它匹配两个匹配组,每个组至少包含 8 位数字; where the two numbers are separated by at least one non-digit character.其中两个数字至少由一个非数字字符分隔。

 let input = document.getElementById("input").innerHTML; let regex = /(\\d{8,})[^\\d]+(\\d{8,})/g; let matches = regex.exec(input); document.getElementById("ans").innerHTML = "OUTPUT: The first num is " + matches[1] + " and the second is " + matches[2];
 <div id="input"> INPUT: 9216143567 is the number and other one is 0112388908 </div><br> <div id="ans"></div>

Edit:编辑:

If you want to extract a dynamic number of numbers, you can use a simpler regex, \\d{8,} .如果要提取动态数量的数字,可以使用更简单的正则表达式\\d{8,} I've also modified the code so it replaces the original number with a URL that directs to it.我还修改了代码,因此它将原始号码替换为指向它的 URL。

 let input = document.getElementById("input").innerHTML; let regex = /\\d{8,}/g; let match; let matches_array = []; while (match = regex.exec(input)) { matches_array.push(match); } for (let i = 0; i < matches_array.length; i++) { let tmp = '<a href="tel:' + matches_array[i] + '" class="button button-positive">' + matches_array[i] + '</a>'; input = input.replace(new RegExp(matches_array[i], "g"), tmp); } document.getElementById("ans").innerHTML = input;
 <div id="input"> 9216143567 is the number and other one is 0112388908 and the third is 1234567890 </div><br> <div id="ans"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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