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