How to replace a certain string within another string in Javascript?

Asked

Viewed 18,454 times

6

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" on the other. How should I proceed?

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

4 answers

13

The simple form is through the function replace() type string. Documentation in English.

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

Behold working in the Codepen. Also put on the Github for future reference.

Thus the variable linha_nova will remain unchanged and the line variable will contain "I AM AFRAID OF DOG". If you need linha_nova is changed, you should save the result in it and not in linha.

You need to have a certain sense of what the content is or it may have unwanted results. You can replace only a part of a word, for example: "HUMBERTO" can become "HMEDO DEBERTO". You may also have problems if you have the substring appearing several times.

But if you want to solve more complex situations this may not be the most appropriate. The function replace allows regular expression syntax as demonstrated in the mgigsonbr response.

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

var linha = linha_nova.substr(0,9) + "MEDO DE" + linha_nova.substr(11, linha_nova.length - 11);

9

Replacing specific positions

To replace only a fixed position or range, just use substring. First take the chunk from the beginning to the starting position you want to replace, then the chunk that starts at the end of the chunk 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 desired beginning and ending, but rather the desired beginning and number of characters.

Replacing specific words

The function replace allows you to replace one substring with another. It also allows you to pass a regular expression, and for each marriage (match) replace it with another string or the result of a function. If you want to replace only the first occurrence, use the string call; if you want all, use a regex with a flag g:

var str = "um cachorro, um gato, um rato";

var uma = str.replace("um", "o"); // o cachorro, um gato, um rato
var alt = str.replace(/um/, "o"); // o cachorro, um gato, um rato

var todas = str.replace(/um/g, "o"); // o cachorro, o gato, o rato

var captura = str.replace(/(um)/g, "xx$1xx"); // xxumxx cachorro, xxumxx gato, xxumxx rato

var funcao = str.replace(/\w+/g, function(match) {
    return Math.random() < 0.5 ? match : match.toUpperCase();
}); // UM cachorro, UM GATO, um rato 

Note that this call creates a new string. In Javascript strings are immutable, so there is no way to change a pre-existing string without creating a new one.

Examples in jsFiddle.

  • if for example I want to replace by position instead of the word as it would be ? Example, I want to replace a letter at position 38. I’d use the substar anyway ?

  • 1

    @user7605 Yes, I think it’s the best way. Like str.substring(0,10) + "x" + str.substring(11,str.length). Note only that substring asks for the beginning and the end, while substr asks for the start and number of characters.

3


You might as well 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)

-2

var linha_nova = "EU TENHO UM CACHORRO";
alert(linha_nova.replace("UM", "CARA DE"));
  • I am the author of this answer and two people downvote. I’m curious why they did this.

Browser other questions tagged

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