How to replace characters from within braces using spli and replace method of Javascript?

Rajnilari2015
Posted by Rajnilari2015 under JavaScript category on | Points: 40 | Views : 1343
Let's say we have the below input

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

We need to remove the comma within the square brackets such that the final output will be

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

Here is a solution for the same

<html>
<head>
<script type='text/javascript'>

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);
}

</script>

</head>
<body>

<button id="btn1" onClick="test()">Test</button>
</div>
</body>
</html>


We split the input by [ character.Then merge the arrays where the second array is replaced by '' for ',' to get the desired output

Comments or Responses

Login to post response