String.replace
String.replace
功能
替换字符串中的匹配内容。字符串模式只替换第一次出现;Regex 参数带 g 标志时替换全部匹配。
语法
string.replace(from, to)
参数
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| from | String/Regex | 否 | '' | 要替换的字符串或正则表达式。 |
| to | Any | 否 | '' | 替换后的内容,调用时会先转为字符串。 |
返回值
| 类型 | 说明 |
|---|---|
| String | 返回替换后的新字符串。 |
示例
text = 'hello js' result = text.replace('js', 'BT') // 输出:hello BT print result
注意事项
- 字符串模式使用单次替换。
- 正则模式是否全局替换由 Regex 的 g 标志决定。