此方法查找正则表达式和字符串之间的匹配,并将匹配的子字符串替换为新的子字符串。
string.replace(regexp/substr, newSubStr/function[, flags]);
regexp - RegExp对象。匹配项被参数#2的返回值替换。
substr - 将被newSubStr替换的字符串。
newSubStr - 替换从参数#1收到的子字符串。
function - 为创建新的子字符串而调用的函数。
flags - 包含RegExp标志的任意组合的字符串:g-全局匹配,I-忽略大小写,m-多行匹配。仅当第一个参数是字符串时,才使用此参数。
它只是返回一个新的更改后的字符串。
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/string-replace.html
来源:LearnFk无涯教程网
<html> <head> <title>JavaScript String replace() Method</title> </head> <body> <script type="text/javascript"> var re=/apples/gi; var str="Apples are round, and apples are juicy."; var newstr=str.replace(re, "oranges"); document.write(newstr ); </script> </body> </html>
运行上面代码输出
oranges are round, and oranges are juicy.
尝试以下示例;它展示了如何切换字符串中的单词。
<html> <head> <title>JavaScript String replace() Method</title> </head> <body> <script type="text/javascript"> var re=/(\w+)\s(\w+)/; var str="zara ali"; var newstr=str.replace(re, "$2, $1"); document.write(newstr); </script> </body> </html>
运行上面代码输出
ali, zara
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)