How to replace characters from within braces using RegularExpression in Javascript?

Rajnilari2015
Posted by Rajnilari2015 under JavaScript category on | Points: 40 | Views : 1390
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 output = input.replace(/\[.*?\]/g, function(match) {return match.replace(/,/g, '');});
}
</script>

</head>
<body>

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


We are using a regular expression replacement. The replacement function receives the part of the input that was matched by the regexp and then it calculates the replacement. In this case is another replace call to remove the commas.

Comments or Responses

Login to post response