matt colley
matt colley

Reputation: 173

CSS String Length

and thanks first of all for looking at my post.

My question today is about CSS. I have a script which connects to a database and creates an XML stream. Within this stream is a telephone number string which is formatted as 8005551212

This XML stream is exploded and parsed into my final page.

However on my final page I need to display this string as (800)555-1212

Does CSS have the capability to convert this string? I have been reading up on `word-wrap: break-word but I may be going down the wrong path....

Thanks Again, --Matt

Upvotes: 3

Views: 786

Answers (3)

Madara's Ghost
Madara's Ghost

Reputation: 174957

CSS cannot achieve this, note the CSS should be used for styling and not for content managing and behaviour.

instead, use JavaScript to achieve this: http://jsfiddle.net/Ke6Ns/

function formatPhone(phone) { 
  return "("+phone.substring(0,3)+")"+phone.substring(3,6)+"-"+phone.substring(6,11); 
}

Upvotes: 0

Spudley
Spudley

Reputation: 168685

Use Javascript for this, not CSS.

Here's a very simple one-line JS regex function to do the job for you:

var formatted_phone = plain_phone.replace(/^(\d{3})(\d{3})(\d{4})$/,"($1)$2-$3");

(note, the line above assumes that the phone number is already known to be in the correct format; it doesn't do any validation)

Hope that helps.

Upvotes: 5

Jason Gennaro
Jason Gennaro

Reputation: 34855

You can do it with javascript like this

var n = '8005551212';
var n1 = n.substring(0,3);
var n2 = n.substring(3,6);
var n3 = n.substring(6,11);

document.write("(" + n1 + ")" + n2 + "-" +n3);

http://jsfiddle.net/jasongennaro/N5Gsu/

Basically, your chopping the string into several pieces and then adding them together again with the new bits you want

If you need to do it for several numbers, you could use a function.

var n = ['8005551212','8005551213','8005551214'];

function formatNumbers(){
    for(var i=0; i<n.length; i++){
        var n1 = n[i].substring(0,3);
        var n2 = n[i].substring(3,6);
        var n3 = n[i].substring(6,11);
        document.write("(" + n1 + ")" + n2 + "-" + n3 + "<br />");
    }
}

formatNumbers(n);

http://jsfiddle.net/jasongennaro/N5Gsu/1/

To build on the comment from @Dennis, switched out document.write for .innerHTML

document.getElementById("a").innerHTML += 
  "(" + n1 + ")" + n2 + "-" + n3 + "<br />";

http://jsfiddle.net/jasongennaro/N5Gsu/2/

Upvotes: 4

Related Questions