Adding quotes to a comma separated string - javascript

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"

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

Javascript-Node.Js reaching dynamic body elements

I have HTML input elements with names like A[1], A[2], A[3]. I want to catch them in express this way:
var optcount = i + 1;
var columnA=req.body['A['+optcount+']'];
However it does not work.
If I have names like A1, then this works:
var columnA=req.body['A'+optcount];
Any suggestions?
For a quick hack,
var optcount = i + 1;
var prop = 'A[' + optcount + ']';
var columnA=req.body[prop];
Should work.
You should be escaping characters to have a better optimized solution, look at these -> Is there a RegExp.escape function in Javascript? and How to escape regular expression in javascript?

Change data inside string with box brackets

I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.
You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego
You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')
For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)
This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);

Adding the single string quote for value inside variable using Javascript

I have a variable, before I use that variable,I need to add string quotes to the value/data which is inside the variable using JavaScript need help
//i am getting like this //
var variable=king;
//i want to convert it with single quote//
variable=variable;
but i need the data inside variable should be in a single quotation.
You can concatenate the variable with your quotes like :
function addQuotes(value){
var quotedVar = "\'" + value + "\'";
return quotedVar;
}
And use it like :
var king = addQuotes('king');
console.log will display :
'king'
Edit : you can try it in the chrome/firefox console, I did it and it works perfectly when copy/paste from here.
var x = 'abc';
var sData = "\'" + x +"\'";
// sData will print "'abc'"
var x = 'pqr';
var sData = "\'" + x +"\'";
// sData will print "'abc'"
1) You can use doublequotes
var variable = "'" + variable + "'";
2) ... or You can escape single quote symbol with backslash
var variable = '\'' + variable + '\'';

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

javascript regex to replace a substring

In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

Categories

Resources