How to replace a given string inside another Javascript string?

4

How can I replace only a certain part of a string ? Example:

var linha_nova = "EU TENHO UM CACHORRO";

I want to replace only the word "UM" with another. How should I proceed?

I also need to replace with the known position of the word to be replaced. For example, I know that "UM" is in tenth place.

    
asked by anonymous 24.05.2014 / 20:10

3 answers

1

You could also be doing:

var frase = "Eu tenho um cachorro(s)";
var novaFrase = frase.replace(frase.substring(9, 11), "dois");

alert(novaFrase); // Eu tenho dois cachorro(s)

Or using regular expressions:

var frase = "Eu tenho um cachorro(s)";
var novaFrase = frase.replace(/(.{9}).{2}/,"$1dois")

alert(novaFrase); // Eu tenho dois cachorro(s)
    
24.05.2014 / 21:17
10

The simple way is through the function replace() of types string . English documentation .

var linha_nova = "EU TENHO UM CACHORRO";
var linha = linha_nova.replace("UM", "MEDO DE");
console.log(linha);

See working on CodePen . Also put it on GitHub for future reference .

In this way the variable linha_nova will remain unchanged and the variable line will contain "I HAVE FEAR OF PUPPY". If you need to% wrap% to be changed, you should save the result to it, not% w / o%.

You need to have a certain notion of what the content is but may have unwanted results. You can substitute only a part of a word, for example: "HUMBERTO" can become "HMEDO DEBERTO". It may also have problems if you have substring appearing multiple times.

But if you want to solve more complex situations this may not be the most appropriate. The linha_nova function allows syntax of regular expressions as demonstrated in mgigsonbr's response.

If you know the position and size of the part of the string you want to change, then use:

var linha = linha_nova.substr(0,9) + "MEDO DE" + linha_nova.substr(11, linha_nova.length - 11);
    
24.05.2014 / 20:21
5

Replacing specific positions

To replace only one position or fixed range, just use substring . First take the piece from the beginning to the starting position you want to replace, then the piece that starts at the end of the stretch to the end of the string:

var linha_nova = "EU TENHO UM CACHORRO";
                //0123456789abcdef
var resultado = linha_nova.substring(0,9) +
                "FOO" +
                linha_nova.substring(11, linha_nova.length);

The function substr also serves, but it receives not the beginning and the end desired, but the beginning and the number of characters desired.

Replacing specific words

The replace function allows you to replace one substring with another. It also allows you to pass a regular expression, and for each match ( match

24.05.2014 / 20:27