Reputation: 13120
I am doing a simple cleanup of phone numbers on my web pages,
In many cases I see human friendly phone numbers, like 1-800-CONTACTS. My current scripting strips out everything except the numbers.
var theValueNumOnly = $.trim($(this).text()).replace(/[^0-9]/g,'');
The value becomes: 1800
Does anyone know a simple snippet that already had the letters-to-numbers converted?
Upvotes: 0
Views: 122
Reputation: 219920
var toPhoneNumber = (function () {
var dict = {
a: 2, b: 2, c: 2,
d: 3, e: 3, f: 3,
g: 4, h: 4, i: 4,
j: 5, k: 5, l: 5,
m: 6, n: 6, o: 6,
p: 7, q: 7, r: 7, s: 7,
t: 8, u: 8, v: 8,
w: 9, x: 9, y: 9, z: 9
}
return function (str) {
return str.toLowerCase().replace(/[^\da-z]/g, '').replace(/([a-z])/g, function (v) {
return dict[v];
});
}
}());
To use it, just pass your string to the toPhoneNumber
function:
var phoneNumber = toPhoneNumber('1-800-CONTACTS');
Here's the fiddle: http://jsfiddle.net/ReGYp/1/
Upvotes: 2
Reputation: 1769
The direct approach (handles upper and lower case):
phone = "1-800-CONTACS"
phone = phone.replace(/[abc]/gi, '2');
phone = phone.replace(/[def]/gi, '3');
phone = phone.replace(/[ghi]/gi, '4');
phone = phone.replace(/[jkl]/gi, '5');
phone = phone.replace(/[mno]/gi, '6');
phone = phone.replace(/[pqrs]/gi, '7');
phone = phone.replace(/[tuv]/gi, '8');
phone = phone.replace(/[wxyz]/gi, '9');
phone = phone.replace(/[^0-9]/g, ' ');
console.log(phone)
=> 1 800 2668227
Upvotes: 0
Reputation: 6089
Here's a post on his topic RegEx for Phone Number Numbers with Letters that provides a PHP solution. You could do this in a regex by mapping each of the 24 letters that convert to numbers. It's probably easier in PHP or python or your favorite language.
Upvotes: 0