replace()是TypeScript中的内置函数,用于查找正则表达式和字符串之间的匹配项,并将匹配的子字符串替换为新的子字符串。句法:
string.replace(regexp/substr, newSubStr/function[, flags]);
参数:此方法接受上述和以下所述的五个参数:
- regexp:此参数是RegExp对象。
- substr:此参数是要替换的字符串。
- newSubStr:此参数是替换子字符串的字符串。
- function:此参数是要用来创建新子字符串的函数。
- flags:此参数是一个包含RegExp标志的任意组合的字符串。
返回值:此方法返回一个新的更改的字符串。
下面的示例说明TypeScriptJS中的String replace()方法:
范例1:
的JavaScript
<script>
// Original strings
var str = "Geeksforgeeks - Good Platform";
var re = /Good/gi;
// Use of String replace() Method
var newstr = str.replace(re, "Best");
console.log(newstr);
</script>
输出:
Geeksforgeeks - Best Platform
范例2:
的JavaScript
<script>
// Original strings
var str = "Geeksforgeeks TypeScript";
var re = /(\w+)\s(\w+)/;
// use of String replace() Method
var newstr = str.replace(re, "$2 $1");
console.log(newstr);
</script>
输出:
TypeScript Geeksforgeeks
相关用法
- Typescript String charAt()用法及代码示例
- Typescript String charCodeAt()用法及代码示例
- Typescript String concat()用法及代码示例
- Typescript String indexOf()用法及代码示例
- Typescript String lastIndexOf()用法及代码示例
- Typescript String localeCompare()用法及代码示例
- Typescript String search()用法及代码示例
- Typescript String slice()用法及代码示例
- Typescript String substring()用法及代码示例
- Typescript String valueOf()用法及代码示例
- Typescript String toString()用法及代码示例
- Typescript String toUpperCase()用法及代码示例
- Typescript String toLowerCase()用法及代码示例
- Typescript String toLocaleUpperCase()用法及代码示例
- Typescript String toLocaleLowerCase()用法及代码示例
- Typescript String substr()用法及代码示例
- Typescript String split()用法及代码示例
注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 TypeScript | String replace() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。