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 ?
– user7605
@user7605 Yes, I think it’s the best way. Like
str.substring(0,10) + "x" + str.substring(11,str.length)
. Note only thatsubstring
asks for the beginning and the end, whilesubstr
asks for the start and number of characters.– mgibsonbr