Add characters before each number

Asked

Viewed 478 times

2

I have a string in a textarea that will be in this format:

2199998888
2188889999
2455556666
2566665555

That is, phone numbers with line break to separate them within the textarea.

My need is to enter the country code into all the phone numbers.

I couldn’t find a simple logic to do it.

The result would be this:

552199998888
552188889999
552455556666
552566665555    
  • I don’t know much about phone number patterns, but if it’s a country code you don’t need to use +? (+552199998888, etc.)

  • 1

    In this specific case I don’t need the@mgibsonbr

1 answer

4


Just break the content into lines and add '55' at the beginning of each. So, for example:

var campo = document.querySelector('textarea');
var linhas = campo.value.split("\n");
var novo = linhas.map(function(item) {
  return item ? '55' + item : item; // se a linha estiver em branco, não acrescenta '55'
}).join('\n');
campo.value = novo;
<textarea rows="5">
2199998888
2188889999

2455556666
2566665555
</textarea>

  • bfavaretto, I added an if there not to show the 55 loose at the end.

  • 1

    @Joaopaulo Alterei again counting on blank lines since it is a very likely situation.

Browser other questions tagged

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