Add character in the middle of a string

Asked

Viewed 23,456 times

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 the string be of such value aabbcc

How can I do that?

5 answers

13


Splitting the string in half

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 for fixed place splitting

Picking 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 on the left and two on the right:

//Index      -4321 
var string = "aacc";
var resultado = string.substr(0,2)+"bb"+string.substr(-2);

Or, taking two on the left and the third on:

var string = "aacc";
var resultado = string.substr(0,2)+"bb"+string.substr(2);

8

Variable "string" takes your text. Variable "m" locates the "middle" of your string. Variable "r" returns the string by adding "bb" to the middle of the text passed.

For this I used substr(0,m) that starts the count of the characters at zero and goes to the middle ("m") that 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);

6

I created a function that concatenates the value determined by you in half the total amount of characters in your text, it returns a string with the value already concatenated.

function Inserir(string, valor)
{
 var i = Math.floor(string.length / 2);
 return string.substr(0, i).concat(valor).concat(string.substr(i));
}

Use: Inserir("aacc", "bb");

4

0

If you mean insert one string into the other:

function inserirTexto(TEXTO_ORIGEM, TEXTO_INSERIDO, INDICE) {
    return(""
        + TEXTO_ORIGEM.substring(0, INDICE)
        + TEXTO_INSERIDO
        + TEXTO_ORIGEM.substring(INDICE)
    );
}

Use: var teste = inserirTexto("Isso é teste.", "um ", 7)

As a result the test variable will be "This is a test."

Browser other questions tagged

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