javascript - 使用 .replace() 时在替换参数上调用方法
问题描述
我最近在玩,.replace()
发现以下行为很奇怪。采取以下两个代码片段:
const str = "Hello world";
const res = str.replace(/(o)/g, "$1".repeat(3));
console.log(res); // Hellooo wooorld (which I expected)
上面的 print "Hellooo wooorld"
,我期望的,因为我.repeat(3)
在匹配的o
字符上使用。
但是,当我应用相同的逻辑并使用.toUpperCase()
时,我的字符串保持不变:
const str = "Hello world";
const res = str.replace(/(o)/g, "$1".toUpperCase());
console.log(res); // Hello world (expected HellO wOrld)
令我惊讶的是,上面的内容不起作用,因为它打印了原始字符串而不是"HellO wOrld"
. 那么,为什么第一个代码片段有效,而第二个无效?. 我知道我可以为此使用替换功能,但我更关心理解为什么第一个片段有效,而第二个无效。
解决方案
计算第二个参数的表达式将替换$#
传递参数中所有出现的 -like 字符串。在第一个代码中,传递的参数是'$1$1$1'
:
const res = str.replace(/(o)/g, "$1".repeat(3));
// interpreter first parses the expression in the second parameter,
// so it knows what to pass to replace:
const res = str.replace(/(o)/g, "$1$1$1");
// THEN the function call occurs
在第二个代码中,调用toUpperCase
结果'$1'
是相同的字符串,$1
:
const res = str.replace(/(o)/g, "$1".toUpperCase());
// interpreter first parses the expression in the second parameter,
// so it knows what to pass to replace:
const res = str.replace(/(o)/g, "$1");
// THEN the function call occurs
推荐阅读
- jquery - jQuery.eCalendar() - 仅在点击日期时显示事件
- python - 不允许我读取 msg 文件的 com_error
- java - 表格中的数据未正确显示,JavaFx 使用 SQLite
- c# - 如何在 WPF 应用程序运行时修改绑定路径
- python - 无法检测带有 blob 的图像
- vue.js - 升级到 vuetify 2.0 后,Vuetify 应用程序变为空白
- php - 从laravel中的复选框中删除选定的行
- c# - 当前上下文中不存在名称“f_name”
- c# - 类型对象会被垃圾收集吗?
- arrays - findIndex 不断从 json 返回 -1