Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace square bracket & curly brackets to round brackets in javascript or jquery

I have a string like this

var data = "{45}*[52]*{45}*[52]*{45}*[52]*69"

I need to replace all the square bracket & curly brackets to round brackets in javascript or jquery

I have tried this

.replace(/[\[\]']+/g,'')

but it replaces all the open and close brackets parallel

Expected result is = "(45)*(52)*(45)*(52)*(45)*(52)*69"

Any ideas ?

like image 557
Suganth G Avatar asked Aug 01 '26 02:08

Suganth G


2 Answers

In a simple way you can use

"{45}*[52]*{45}*[52]*{45}*[52]*69".split(/[\{\[]/).join('(').split(/[\}\]]/).join(')')
like image 101
Harpreet Singh Avatar answered Aug 02 '26 15:08

Harpreet Singh


You can call .replace() with a function as the second parameter. With this function you can create a new substring which will be used as replacement.

str.replace(regexp|substr, newSubStr|function[, flags])

function (replacement)
A function to be invoked to create the new substring (to put in place of the substring received from parameter 1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.

Specifying a function as a parameter
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

"[abc]".replace(/\[|\]/g, function(m) {
    var replacements = {"[": "(", "]": ")"}; return replacements[m];
});
like image 40
Andreas Avatar answered Aug 02 '26 15:08

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!