Adding quotes to a comma separated string

Viewed 5997

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"

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

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

The naive solution to your problem looks like this:

> line = '1.1.1.1,2.2.2.2,3.3.3.3'
'1.1.1.1,2.2.2.2,3.3.3.3'
> '"' + line.replace(/,/g, '","') + '"'
'"1.1.1.1","2.2.2.2","3.3.3.3"'

or if the quotes need to be reversed:

> "'" + line.replace(/,/g, "','") + "'"
'\'1.1.1.1\',\'2.2.2.2\',\'3.3.3.3\''

However, it sounds like what you need is a full-blown CSV parser, to handle cases in which you have quotes and commas and new lines and other crazy characters embedded in your input.

The naive solution seems to be in line, though, with what you were trying to do, and might illustrate why your approach fell short.

Your code works as you intended. Can you append to c without declaring?

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; b++)
{
    c.concat("\'").concat(b[i]).concat("\',\"")
    console.log(b)
}

You can store several values in a variables by using array for example. If you want to get string like '"1.1.1.1","2.2.2.2","3.3.3.3"' you can use the following code:

var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = a.split(',').map(function (str) {
  return '"' + str+ '"';
}).join(',');
console.log(b);

Related