JavaScript replace() Method: Replace String Values
The JavaScript 'replace()' method is used to replace a specified value or regular expression with a new value. It returns a new string with the replaced value.
Syntax:
string.replace(searchValue, newValue)
Parameters:
- 'searchValue': The value or regular expression to be replaced.
- 'newValue': The new value to replace the 'searchValue' with.
Example 1: Replacing a single occurrence of a value
let str = 'Hello World';
let newStr = str.replace('World', 'JavaScript');
console.log(newStr); // Output: Hello JavaScript
Example 2: Replacing all occurrences of a value using a regular expression with the 'g' flag
let str = 'Hello World, World';
let newStr = str.replace(/World/g, 'JavaScript');
console.log(newStr); // Output: Hello JavaScript, JavaScript
Note: By default, the 'replace()' method only replaces the first occurrence of the 'searchValue'. To replace all occurrences, use a regular expression with the 'g' (global) flag.
原文地址: http://www.cveoy.top/t/topic/feom 著作权归作者所有。请勿转载和采集!