JavaScript字符串。replace()方法

下面是字符串的示例。replace()方法。

null
  • 例子:

javascript

<script>
var string = 'GeeksForGeeks' ;
var newstring = string.replace(/GeeksForGeeks/, 'GfG' );
document.write(newstring);
</script>


  • 输出:
GfG

这个 一串替换() 是JavaScript中的一个内置方法,用于用另一个字符串或正则表达式替换给定字符串的一部分。原始字符串将保持不变。 语法:

str.replace(A, B)

参数: 这里参数A是正则表达式,B是一个字符串,它将替换给定字符串的内容。 返回值: 它返回一个包含替换项的新字符串。 显示此方法工作的JavaScript代码: 代码#1: 这里,Geeksforgeks字符串的内容将被gfg替换。

javascript

<script>
// Assigning a string
var string = 'GeeksForGeeks is a CS portal' ;
// Calling replace() method
var newstring = string.replace(/GeeksForGeeks/, 'gfg' );
// Printing replaced string
document.write(newstring);
</script>


输出:

gfg is a CS portal

代码#2:

javascript

<script>
// Taking a regular expression
var re = /GeeksForGeeks/;
// Taking a string as input
var string = 'GeeksForGeeks is a CS portal' ;
// Calling replace() method to replace
// GeeksForGeeks from string with gfg
var newstring = string.replace(re, 'gfg' );
// Printing new string with replaced items
document.write(newstring);
</script>


输出:

gfg is a CS portal

支持的浏览器:

  • 谷歌Chrome 1及以上版本
  • 边缘12及以上
  • Firefox 1及以上版本
  • Internet Explorer 5.5及以上版本
  • 歌剧4及以上
  • Safari 1及以上
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享