Add character in the middle of a string

6

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?

    
asked by anonymous 23.04.2014 / 19:20

5 answers

11

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);
    
23.04.2014 / 19:23
7

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);
    
23.04.2014 / 20:08
6

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");

    
23.04.2014 / 19:37
3

Solution

var string = "aacc";
var final  =  string.substring(0,2) + "bb" + string.substring(2);

Links: link

    
23.04.2014 / 19:24
0

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."

    
16.05.2018 / 23:41