我想知道如何在JavaScript中用大写替换捕获组。这是我到目前为止尝试的一个简化版本,但不起作用:
> a="foobar"
'foobar'
> a.replace( /(f)/, "$1".toUpperCase() )
'foobar'
> a.replace( /(f)/, String.prototype.toUpperCase.apply("$1") )
'foobar'
你能解释一下这段代码有什么问题吗?
发布于 2018-02-27 01:34:09
旧帖子,但值得将@ChaosPandion answer扩展到其他具有更多限制RegEx的用例。例如,确保使用特定格式的/z(f)oo/
包围(f)
或捕获组
> a="foobazfoobar"
'foobazfoobar'
> a.replace(/z(f)oo/, function($0,$1) {return $0.replace($1, $1.toUpperCase());})
'foobazFoobar'
// Improve the RegEx so `(f)` will only get replaced when it begins with a dot or new line, etc.
我只想强调一下function
的两个参数,这两个参数使得查找特定格式和替换格式中的捕获组成为可能。
发布于 2019-02-24 07:38:37
给定一个属性、值的字典(对象,在本例中是一个Map
),并使用.bind()
,如答案部分所述
const regex = /([A-z0-9]+)/;
const dictionary = new Map([["hello", 123]]);
let str = "hello";
str = str.replace(regex, dictionary.get.bind(dictionary));
console.log(str);
使用JavaScript普通对象,并定义函数以获取该对象的返回匹配属性值,如果未找到匹配,则返回原始字符串
const regex = /([A-z0-9]+)/;
const dictionary = {
"hello": 123,
[Symbol("dictionary")](prop) {
return this[prop] || prop
}
};
let str = "hello";
str = str.replace(regex, dictionary[Object.getOwnPropertySymbols(dictionary)[0]].bind(dictionary));
console.log(str);
https://stackoverflow.com/questions/6142922
复制相似问题