Reputation: 1163
I am working in a project which it needs to get a phone number from a string. the string is like this in Java Script array named dine
{
"group": 1,
"tel1": "Tél(1): 05.82.77.31.78",
"tel2": "Tél(2): 09.55.86.31.45",
},
,...
I want to use pure phone numbers in a tag like this
<a href="tel:0970500469">Tél: 09.70.50.04.69</a>
I have used this java script codes
for (var i = 0; i < dine.length; i++) {
telnom = dine[i].tel1;
telnom = telnom.replace(/\D/g, '');
alert(telnom);
telnom2 = dine[i].tel2;
telnom2 = telnom2.replace(/\D/g, '');
alert(telnom2);
infoHtml += '<div class="info">\n <p> <a href="tel:' + telnom + '">' + dine[i].tel1 + '</a></p>\n <p> <a href="tel:' + telnom2 + '">' + dine[i].tel2 + '</a></p>\n \n</div>';
}
the problem is that it added 1 at the beginning of my phone number that it seems belongs to the Tél(1)
and makes the telnom1 like this : 10970500469
while I want to call 0970500469
I am sure the problem stand for the way I used replace codes but I really do not know how to correct it.
telnom = dine[i].tel1;
telnom = telnom.replace(/\D/g, '');
telnom2 = dine[i].tel2;
telnom2 = telnom2.replace(/\D/g, '');
I really appreciate any help. thank you
Upvotes: 1
Views: 69
Reputation: 2051
You can use the following regex to get the desired telephone number:
var n = "Tél(1): 05.82.77.31.78".match(/[\d]\d+/g).join("");
console.log(n);
Explanation: [\d]
matches only numbers and we are adding another \d so only two numbers which are side-by-side matches. Next, we join them to a single string. If you need number instead of the string you can do following:
Number(n)
Upvotes: 1
Reputation: 1263
If your phone numbers always start with something like Tel:
, Tel(1):
etc you could, for example, consider simply splitting the whole string first using :
(or a space) as separators. Like this:
telnom = dine[i].tel1;
telnom = telnom.split(":")[1].replace(/\D/g, '');
Upvotes: 1
Reputation: 12737
You need to remove any digits that appear within brackets, as well as non digits. Your regext should be /(\(\d*\)|\D)/g
var telnom = "Tel:(1) - 05.34.36.15"
telnom = telnom.replace(/(\(\d*\)|\D)/g, '');
console.log(telnom); //05343615
Upvotes: 2