1
 sampleText='6501-*-5-[*]'

预期产出

 result='6501-%-5-[*]'

我必须将 * 替换为 % 并保持 [*] 原样。两者可能会多次出现。我们怎么能在javascript中做到这一点。提前致谢。

4

2 回答 2

0

尝试这个:

sampleText = sampleText.replace(/\*/g, function(match, offset){
    if(offset > 0) {
        if(sampleText[offset - 1] == '[' && sampleText[offset + 1] == ']'){
            return match;
        }
    }
    return '%';
});

小提琴:这里

于 2013-10-07T12:45:08.170 回答
0

您可以使用 String.replace() 方法。文档在这里

例如:

text = '6501-*-5-[*]';
text = text.replace('-*-','-%-');
console.log(text); // 6501-%-5-[*]
于 2013-10-07T12:34:08.630 回答