Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding quotes to a comma separated string

What I have:

var a = "1.1.1.1,2.2.2.2,3.3.3.3"

What I need:

var a = '1.1.1.1','2.2.2.2','3.3.3.3'

What I'm trying:

var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c
for (var i=0;i<b.length; i++)
    {
        c.concat("\'").concat(b[i]).concat("\',\"")
    }

What I'm actually getting with the above

"'1.1.1.1','"

I'm only able to get the first element right, how do I rectify this? Also, in JS, is it even possible to have something like '1.1.1.1','2.2.2.2','3.3.3.3' stored in a variable?

A background to this problem:

I have an iframe whose source is a kibana query. The query in fact takes in values to a particular parameter in the above mentioned format.

Eg: params:!('1.1.1.1','2.2.2.2')

While my db contains the param values as a string of CSV.

Eg. "1.1.1.1,2.2.2.2,3.3.3.3"

like image 685
blueren Avatar asked Jul 12 '26 12:07

blueren


2 Answers

Try this

var a = "1.1.1.1,2.2.2.2,3.3.3.3";

var b = "'" + a.split( "," ).join( "','" ) + "'";

console.log( b );
like image 63
gurvinder372 Avatar answered Jul 15 '26 02:07

gurvinder372


You don't need to deal with iterations for this, use a RegExp replace:

var a = "1.1.1.1,2.2.2.2,3.3.3.3";

var b = "'" + a.replace(/,/g, "','") + "'";

console.log( b );
like image 40
Amit Avatar answered Jul 15 '26 03:07

Amit



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!