Javascript`替换`替换后备

时间:2015-03-09 00:29:14

标签: javascript regex

采用以下示例:

var tag_oh_so_alone_ = '[FieldName]',
    tag_with_default = '[FieldName:The default value]',
    the_regex = /\[([a-z]+)(\:([^\]]+))?\]/i;

console.log(
    "Results:\n",
    tag_oh_so_alone_.replace(the_regex,"1: $1\n 2: $2\n 3: $3\n"),
    tag_with_default.replace(the_regex,"1: $1\n 2: $2\n 3: $3\n")
);

控制台显示:

Results:
 1: FieldName
 2: 
 3: 
 1: FieldName
 2: :The default value
 3: The default value

我想做的是,在替换声明中(换句话说,我们包含#34; $ 1&#34等的地方),基本上指定:if $3是填充使用$3,否则使用$1

预期输出如下:

  

tag_oh_so_alone_ => FieldName

     

tag_with_default => The default value

这可能吗?

1 个答案:

答案 0 :(得分:3)

你可以pass a function as the replacer String.replace,就像这样

function replacer(match, p1, p2, p3) {
    if (p3) {
        return "1: " + p1 + "\n 2: " + p2 + "\n 3: " + p3 + "\n"
    } else {
        return "1: " + p1 + "\n 2: " + p1 + "\n 3: " + p1 + "\n"
    }
}

console.log(
    "Results:\n",
    tag_oh_so_alone_.replace(the_regex, replacer),
    tag_with_default.replace(the_regex, replacer)
);

,输出变为,

Results:
 1: FieldName
 2: FieldName
 3: FieldName
 1: FieldName
 2: :The default value
 3: The default value

此处,p1p2p3是实际匹配的群组。如果未填充/匹配p3,则它将为undefined。您可以在replacer函数中自定义函数的返回值。