Q:

replace string method js

var str = "JavaScript replace method test";
var res = str.replace("test", "success");  
//res = Javscript replace method success
17
let startText = "Yes, I said yes, it is, yes."

// Replace with no modifiers
let newText = startText.replace("yes", "no")
console.log(newText)  // "Yes, I said no, it is, yes."

// Replace with 'g'-global modifier
newText = startText.replace(/yes/g, "no")
console.log(newText)  // "Yes, I said no, it is, no."

// Replace with modifiers 'g'-global and 'i'-case insensitive
newText = startText.replace(/yes/gi, "no")
console.log(newText)  // "no, I said no, it is, no."
9

var str = "Mr Blue has a blue house and a blue car";

var res = str.replace(/blue/g, "red");
 
12
var str = "Visit Websites!";

var res = str.replace("Websites", "Grepper");
 
2
var str = "Visit Microsoft!";

var res = str.replace("Microsoft", "W3Schools");

console.log(res);
/*Result
Visit W3Schools!
*/
7
let string = 'soandso, my name is soandso';

let replaced = string.replace(/soandso/gi, 'Dylan');

console.log(replaced); //Dylan, my name is Dylan
9
let re = /apples/gi; 
let str = "Apples are round, and apples are juicy.";
let newstr = str.replace(re, "oranges"); 
console.log(newstr)

output:

"oranges are round, and oranges are juicy."
0
const p = 'hello world ! hello everyone ! ';

const regex = /hello/gi;

console.log(p.replace(regex, 'good morning'));
// expected output: "good morning world ! good morning everyone !"

console.log(p.replace('hello', 'good evening'));
// expected output: "good evening world ! hello everyone !"
1
var str = "Hello World";
var res = str. reaplace("World", "Simon");
output result = Hello simon
0
const p = 'Its going to rain today and its going to rain tomorrow';

// Example of replacing all occurrances

// g = global search, which searches all instances
// i = case insensitive, which will match 'a' with 'A'
const regex = /rain/gi;
console.log(p.replace(regex, 'snow'));
// expected output: "Its going to snow today and its going to snow tomorrow"

// Example of replacing the first occurance
console.log(p.replace('rain', 'snow'));
// expected output: "Its going to snow today and its going to rain tomorrow"
5

New to Communities?

Join the community