从大括号内替换字符的有效方法是什么

What will be the efficient way to Replace characters from within braces?

本文关键字:有效 方法 是什么 字符 替换      更新时间:2023-09-26

>我有以下输入

var input = (a-d){12-16},(M-Z){5-8},[@$%!^,12+-,23^!] 

我需要删除方括号内的逗号,以便最终输出为

var output = (a-d){12-16},(M-Z){5-8},[@$%!^12+-23^!] 

按解决方案

function test()
{
    var input = '(a-d){12-16},(M-Z){5-8},[@$%!^,12+-,23^!]'; //input string
    var splitByFirstBracket = input.split("["); //split the input by [ character    
    //merge the arrays where the second array is replaced by '' for ','
    var output = splitByFirstBracket[0] + '[' + splitByFirstBracket[1].replace(/,/g,'');    
    alert(output);
}

它正确地提供输出。有没有更好的方法 - 我对JavaScript和JQuery都开放。

提前致谢

您可以使用正则表达式替换。替换可以是一个函数,它接收与正则表达式匹配的输入部分,然后它可以计算替换。在这种情况下,它将使用另一个替换调用来删除逗号。

var input = '(a-d){12-16},(M-Z){5-8},[@$%!^,12+-,23^!]'; //input string
var output = input.replace(/'[.*?']/g, function(match) {
  return match.replace(/,/g, '');
});
console.log(output);