JavaScript 替换字符串中的字符程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例:替换字符串中的第一个字符出现

// program to replace a character of a string

const string = 'Mr Red has a red house and a red car';

// replace the characters
const newText = string.replace('red', 'blue');

// display the result
console.log(newText);

输出

Mr Red has a blue house and a red car

在上面的程序中,使用 replace() 方法将指定的字符串替换为另一个字符串。

replace() 方法中传递字符串时,它只替换字符串中的第一个匹配项。因此,如果字符串中有第二个匹配项,它将不会被替换。


您也可以将正则表达式(regex) 传递到 replace() 方法中以替换字符串。

示例 2:使用 RegEx 替换字符串中的字符

// program to replace a character of a string

const string = 'Mr Red has a red house and a red car';

// regex expression
const regex = /red/g;

// replace the characters
const newText = string.replace(regex, 'blue');

// display the result
console.log(newText);

输出

Mr Red has a blue house and a blue car

在上面的程序中,在 replace() 方法中使用正则表达式作为第一个参数。

/g 表示全局。这意味着字符串中所有匹配的字符都会被替换。

由于 JavaScript 区分大小写,Rr 被视为不同的值。

您还可以使用正则表达式通过 /gi 进行不区分大小写的替换,其中 i 表示不区分大小写。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战