Limit text to be selected from input with Javascript

Asked

Viewed 78 times

0

I would like to know how to limit the value to be selected with Javascript.

For example, I want to take only the country indicator of the number typed, but it is different the amount of characters for each country, type, Brazil has 3 "+55", whereas the United States has only 2 "+1".

How do I get the JS to select only this indicator from that code that selects the input value:

$(this). val();

Remembering that soon after the country indicator will come a "(", for example, "+99(99)99999-9999".

2 answers

1

Here I am using the substring function that will return all the content in the string that exists before the character "(", that is, from position 0 to where there is the character I want to limit.

let numeroTelefone = '+55(31)90000-5000';
let codigoPais;
codigoPais = numeroTelefone.substring(0, numeroTelefone.indexOf("("));

In this case, only the string "+55 will be returned".

1


Using the regex below with .match() you can get the code:

\+\d{1,3}

The pattern will capture the + followed by 1 to 3 numbers.

Example:

$("input").on("focus", function(){
   
   var ddi = $(this).val().match(/\+\d{1,3}/)[0];
   console.log(ddi);
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Clique num input abaixo:
<br>
<input type="text" readonly value="+9(99)99999-9999">
<br>
<input type="text" readonly value="+99(99)99999-9999">
<br>
<input type="text" readonly value="+999(99)99999-9999">

Browser other questions tagged

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