Problem
How to add character in the middle of a javascript string?
For example:
var string = "aacc"; // eu quero colocar as letras bb no meio da aa e cc
I want string
to have this value aabbcc
How can I do this?
How to add character in the middle of a javascript string?
var string = "aacc"; // eu quero colocar as letras bb no meio da aa e cc
I want string
to have this value aabbcc
How can I do this?
Splitting the string in the middle
var string = "aacc";
var metade = Math.floor(string.length / 2);
var resultado = string.substr(0,metade)+"bb"+string.substr(metade);
// o código abaixo é só para teste:
document.getElementById('resultado').innerHTML = resultado;
<div id="resultado"></div>
Results:
// "aacc"=> "aabbcc"
// "aaaccc"=> "aaabbccc"
// "batata"=> "batbbata"
Alternatives to Split at a Fixed Location
Taking two characters from the first (starts from 0) onwards, and two from the third:
//Index: 0123
var string = "aacc";
var resultado = string.substr(0,2)+"bb"+string.substr(2,2);
Alternatively, taking two from the left and two from the right:
//Index -4321
var string = "aacc";
var resultado = string.substr(0,2)+"bb"+string.substr(-2);
Or, taking two from the left and the third onwards:
var string = "aacc";
var resultado = string.substr(0,2)+"bb"+string.substr(2);
Variable "string" receives your text. Variable "m" locates the "middle" of your string. Variable "r" returns string by adding "bb" to the middle of the passed text.
For this I used substr (0, m) which starts counting the characters at zero and goes to the middle ("m") which is concatenated with "bb" and concatenated to what is left of the broken string.
var string = "aacc";
var m = Math.floor(string.length / 2);
var r= string.substr(0,m)+"bb"+string.substr(m);
I created a function that concatenates the value that you determined in half the total amount of characters in your text, it returns a string with the already concatenated value.
function Inserir(string, valor)
{
var i = Math.floor(string.length / 2);
return string.substr(0, i).concat(valor).concat(string.substr(i));
}
Usage: Inserir("aacc", "bb");
Solution
var string = "aacc";
var final = string.substring(0,2) + "bb" + string.substring(2);
Links: link
If you meant to insert a string into the other:
function inserirTexto(TEXTO_ORIGEM, TEXTO_INSERIDO, INDICE) {
return(""
+ TEXTO_ORIGEM.substring(0, INDICE)
+ TEXTO_INSERIDO
+ TEXTO_ORIGEM.substring(INDICE)
);
}
Usage: var teste = inserirTexto("Isso é teste.", "um ", 7)
As a result the test variable will be "This is a test."