string js replace code example

Example 1: javascript replace string

var str = "JavaScript replace method test";
var res = str.replace("test", "success");  
//res = Javscript replace method success

Example 2: string replace javascript

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."

Example 3: javascript replace

// Valor retornado: “Aprendendo JavaScript. JavaScript é na DevMedia”
exemplo = "Aprendendo Javascript. JAVAScript é na DevMedia ";
resultado = exemplo.replace(/javascript/gi, "JavaScript");

Example 4: javascript string replace

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"

Example 5: replace in string javascript

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 !"

Example 6: replace javascript

// 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."

Tags:

Misc Example