Javascript-正则表达式

时间:2013-10-07 12:27:16

标签: javascript

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

预期输出

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

我必须将*替换为%并保留[*]。两者都可能有多次出现。 我怎么能在javascript中做到这一点。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用String.replace()方法。文档here

例如:

text = '6501-*-5-[*]';
text = text.replace('-*-','-%-');
console.log(text); // 6501-%-5-[*]

答案 1 :(得分:0)

试试这个:

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

小提琴:here