I want to make a smart replacement for a regular expression to search for phones in the text and design them as links

there is a test line with different phone variations

var t = '+79995260644 |sdafdsa| +7 747 526 06 44 | +7 (232) 744-33-22 | +7 (232) 333 33 33 | +7 (4569) 777 8877 | 8 (456) 777 8877'; 

there is a regular expression to search for

  var reg = /(\+7|8)[- _]*\(?[- _]*(\d{3}[- _]*\)?([- _]*\d){7}|\d\d[- _]*\d\d[- _]*\)?([- _]*\d){6})/g; 

I tried at the beginning:

 var r = t.replace(reg, "<a href='tel:$&'>$&</a>"); $('#bb').html(r); //выводим результат в блок для просмотра 

but this method is not perfect because in href it is not desirable to have spaces and other characters except numbers. After reading the manuals I decided to figure out in my own way through the function

  var v = t.replace(reg, function(str,tel,off,s) { return "<a href='tel:"+tel.replace(/[-+()]/g,"")+"'>"+tel+"</a>"; }); $('#bb').html(v); 

but why the result is so

  <a href="7">+7</a> |sdafdsa| <a href="7">+7</a> | <a href="7">+7</a> | <a href="7">+7</a> | <a href="7">+7</a> | <a href="8">8</a> 

Why is it beginning to cut in such processing, please tell me how to properly?

ps: is it correct that this expression tel.replace (/ [- + ()] / g, "") will remove three, pluses, brackets and spaces from the string ??

  • one
    /[-\s()+]/g That literally yesterday I solved this problem myself. Such a regular will leave only numbers from the number. - Alex Sazonov
  • @AlexSazonov thanks)) and what's wrong with the function in the main regular program? Most likely, I did not understand what the principle of the function as the 2nd argument is that it began to cut everything so \ \ dantelol
  • one
    .replace(/[-+()]/g,"") will remove all the parentheses, cons and pros, but not spaces, for which \s needed. - Wiktor Stribiżew

1 answer 1

 // Для тестовой строки var t = '+79995260644 |sdafdsa| +7 747 526 06 44 | +7 (232) 744-33-22 | +7 (232) 333 33 33 | +7 (4569) 777 8877 | 8 (456) 777 8877'; t = t.replace(/[^\d+|]/gi, '').replace(/([+\d]+)/gi, '<a href="tel:$1">$1</a>'); console.log(t); // Для внутритекстовой замены t = 'Lorem ipsum +79995260644 dolor sit amet +7 747 526 06 44 consectetur adipisicing elit +7 (232) 744-33-22. Impedit a ipsa obcaecati +7 (232) 333 33 33 saepe natus similique +7 (4569) 777 8877 quas rerum? Nobis repellat, totam eos 8 (456) 777 8877 autem corporis eum ratione omnis eveniet impedit nemo accusamus.'; t = t.replace(/(\+?\d[\d ()_-]+\d)/gi, function(str) { return '<a href="tel:' + str.replace(/[^\d+|]/gi, '') + '">' + str + '</a>'; }); document.querySelector('#text').innerHTML = t; 
 <div id="text"></div>