String Manipulation in Javascript?

Asked

Viewed 130 times

5

I have the following code

var wcalcAlm = ('0140')
alert(wcalcAlm)
//retorno esperado ('01:40')

I need that after the 2 position of the variable wcalcAlm be included :, thus having the following return 01:40?

4 answers

7


Just do the following:

function adicionarTexto(str, caracter, indice){
  return str.slice(0, indice) + caracter + str.slice(indice)
}

var wcalcAlm = ('0140')
console.log(adicionarTexto(wcalcAlm, ':', 2))

This adds a character (or a string) from the index you send.

4

You have this solution:

wcalcAlm.replace(/(\d{2})/,'$1:');
  • replace will go through the whole amount.
  • /(\d{2})/ with Regex I will take the digits and break in the second position.
  • after having separated it creates a mask after the first group, with the character :.
  • and gathered in the way expected.

var wcalcAlm = ('0140');
console.log(wcalcAlm.replace(/(\d{2})/,'$1:'));

2

Another way:

//Duas linhas:
var wcalcAlm = ('0140').split("");
console.log(wcalcAlm[0] + wcalcAlm[1] + ":" + wcalcAlm[2] + wcalcAlm[3]);

2

I’ll put two more options on how we can achieve the desired result:

//Opção com array
const arr = '0140'.split('');
arr.splice(2,0,':');

console.log(arr.join(''));

//Opção com regex
let i = 0;
console.log('##:##'.replace(/#/g, () => '0140'[i++]));

Browser other questions tagged

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