0

我正在寻找一种解决方案来替换前后没有括号的子字符串(id)。

这是我当前的代码,非常简单:

'deal[ptions_attributes][0][price]'.replace(/\[\d+\]/, '[new_id]'));
result: deal[ptions_attributes][new_id][price]

所以我真的不会在新 id 中使用括号 - '[new_id]' 来替换子字符串。有没有办法在替换并保持干净的 'new_id' 时忽略第一个 '[' 括号?

4

4 回答 4

2

这假设没有其他字符串[...]以数字结尾

/\d+(?=\])/
于 2012-12-06T13:17:50.483 回答
1

您可以通过环视来做到这一点:

/(?<=\[)\d+(?=\])/

将匹配括号之间的数字,该数字必须存在才能使匹配成功,但不会成为匹配的一部分。

但正如评论中所说,后面的 ((?<=...)在 javascript 中不起作用。所以我不确定你想要的是否可能。

于 2012-12-06T13:15:53.113 回答
0

你可以试试这样的。

'deal[ptions_attributes][0][price]'.replace(
    /(\[)\d+(\])/,
    function(matchedString,firstCaptureGroup,secondCaptureGroup){
        return firstCaptureGroup + 'new_id' + secondCaptureGroup;
    }
);

You're basically capturing the "[" and "]" in capture groups and then putting them back into the output. This ensures that you capture the correct content but doesn't end up forcing you to include the brackets in your output string. You could easily extend this to match any strings before and after the ID you want to replace.

于 2012-12-06T13:32:49.057 回答
0

I am unsure as to the exact nature of your problem but can you not use :

 '[' + 'new_id' + ']'

This allows you to use a variable in place of 'new_id' which may be your intent.

于 2012-12-06T13:36:04.977 回答