-2

Is there a way to replace something like this:

testHoraciotestHellotest

And replace the 'test' word via javascript, I've tried with the .replace() function but it didn't work

Horacio Garza
  • 45
  • 2
  • 7

3 Answers3

0

It's simple.

var str = "testHoraciotestHellotest";
var res = str.replace("test", "test1");
console.log(res);

If you want to replace all occurances of 'test' rather than just one, use the following trick instead:

var res = str.split("test").join ("test1");

VHS
  • 9,534
  • 3
  • 19
  • 43
0

str.replace() also accepts regular expressions, so you can use /test/g to match all instances of 'test' in the string.

var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "replaced");
console.log(res);
tklg
  • 2,572
  • 2
  • 19
  • 24
0

use g to make a global replace to the string

var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "word");
console.log(res);
gavgrif
  • 15,194
  • 2
  • 25
  • 27