Doubt Data with PHP and JS

Asked

Viewed 60 times

0

Hi I don’t know anything about JS and I wonder if I can edit a field whose value came from the database using javascript? Because I saved in the bank the date of birth and the phone of a customer,and at the time of registration I saved the phone without the Mask and the date in the standard Year-Month-Day.

I wonder if it is possible to use js to format these values coming from the bank so that it is displayed so phone (99) 99999-9999 and date 99/99/9999.

Note : I only asked this question because I could not find anything on google.

2 answers

3

What you look for are regular expressions, through which you can find and modify parts of strings:

Exemplifying: I have the value of the bank printed on the page:

<p class="phone">1199999999</p>

Modifying text inside the p tag:

 $(".phone").text(function(i, text) {
    text = text.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
    return text;
});

Online example in Jsfiddle: https://jsfiddle.net/wsh9modu/1/

More about regular expressions in javascript: https://www.todoespacoonline.com/w/2014/04/expressoes-regulares-em-javascript/

  • Thanks to everyone and especially to Eduardo Kawanaka, I was able to solve the problem using these expressions that he indicated.

1

Generic formatting with dynamic mask:

function format_string(mask, str, ch) {
	ch = (typeof ch === "undefined") ? "#" : ch;
    var c = 0, r = "", l = mask.length;
    for (i = 0; i < l; i++) r += ((mask.substring(i, (i+1)) == ch) ? str.substring(c, ++c) : mask.substring(i, (i+1))); 
    return r;
}

str = '05055344410'; // Exemplo para telefone
document.write(format_string('###-####-####', str));

str = '20150827'; // Exemplo para datas
document.write("<br />"+format_string('####-##-##', str));

str = '100000'; // Exemplo para horário
document.write("<br />"+format_string('##:##:##', str));

str = '45564646456'; // Exemplo para cpf
document.write("<br />"+format_string('###.###.###-##', str));

str = '85282224448'; // Exemplo para qualquer outro formato, um telefone com código do país.
document.write("<br />"+format_string('+### ####-####', str));

The routine is based on another response with PHP. If you are interested in the function written in PHP, read the post: /a/82687/4793

Note that you do not need libraries or plugins.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.