开发者

CSS String Length

and thanks first of all for 开发者_如何学Clooking 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


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.


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/


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); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜