sampleText='6501-*-5-[*]'
预期产出
result='6501-%-5-[*]'
我必须将 * 替换为 % 并保持 [*] 原样。两者可能会多次出现。我们怎么能在javascript中做到这一点。提前致谢。
sampleText='6501-*-5-[*]'
预期产出
result='6501-%-5-[*]'
我必须将 * 替换为 % 并保持 [*] 原样。两者可能会多次出现。我们怎么能在javascript中做到这一点。提前致谢。
尝试这个:
sampleText = sampleText.replace(/\*/g, function(match, offset){
if(offset > 0) {
if(sampleText[offset - 1] == '[' && sampleText[offset + 1] == ']'){
return match;
}
}
return '%';
});
小提琴:这里
您可以使用 String.replace() 方法。文档在这里。
例如:
text = '6501-*-5-[*]';
text = text.replace('-*-','-%-');
console.log(text); // 6501-%-5-[*]