How to prevent values from being converted to strings in javascript? - javascript

var str;
var displayedNum;
for (i in imgURLArray){
str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
$("ul.selection-list").append(str);
}
I need to do this within a loop, but what happens is it prints out "11" instead of "2", because it converts to string before addition.
I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.
Number(1+1) still converts to string first before turning it into a number, so it comes out 11.

Use parenthesis:
var str = "foobar" + (1+i) + "other stuff";
I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.
It should not. My guess is that you are doing something wrong there too.
Update: It seems you are converting i to a string somewhere in the code you did not post.
Update 2: Don't use for..in to loop over an array. Use a normal for loop if it is really an array:
for(var i = 0, l = imgURLArray.length; i < l; i++)
But if it is an objects:
for...in will always set i as a string (as it loops over the properties of the object which are not always integers) . That means you would have to convert i before you do any addition:
... + (1 + (+i)) + ...
Update 3:
You don't always have to use such an "explicit" for loop. For example, you can traverse the array in reverse order, which makes the head shorter:
for (var i = imgURLArray.length; i--; ) {
str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
$("ul.selection-list").prepend(str);
}

Try wrapping numbers in Number()
Like:
var i = 1;
var str = "foobar" + Number(1+i) + "other stuff";

var str = "foobar" + (1+i) + "other stuff";

You could just use the parseInt method:
var str = "foobar" + (parseInt(1+i)) + "other stuff";

The reason is due to your loop:
for (i in imgURLArray){
This iterates over all the property names of imgURLArray as strings. So you will need to use Number() to convert i to an integer:
str = "<li photonum="+i+">" + "<a>"+ (1+Number(i)) + "</a>" + "</li>";

Related

array of strings inside string in jQuery

I need to give array of strings inside string.
my array will be ["2", "3"]
i += "{\"name\":\"" + args.Name + "\",\"values\":[\"" + value + "\"]
What I need:
"{"name":"category1",,"values":["1"]},{"name":"category2","values":["2","1"]
Actual output:
"{"name":"category1",,"values":["1"]},{"name":"category2","values":["2,1"]
The double quotes of values removing and make it as string array. How to achieve this?
Thanks in advance :)
Try to split your value by ,.
i += "{\"name\":\"" + args.Name + "\",\"values\":[\"" + value.split(',') + "\"]
// ----------------------------------------------------------^^^^^^^^^^^-------
try join() function of jQuery
var value = ["2","3"];
var output = "{\"name\":\"Test\",\"values\":[\"" + value.join('","')+ "\"]";
console.log(output);

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

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

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

Replace multiple occurence string using array element

I have several strings in an associative array:
var arr = {
'============================================': '---------',
'++++++++++++++++++++++++++++++++++++++++++++': '---------',
'--------------------------------------------': '---------'
};
I want to replace occurrences of each key with the corresponding value. What I've come up with is:
for (var i in arr)
{
strX = str.replace(i, arr[i]);
console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}
This works, but only on first occurence. If I change the regex to /i/g, the code doesn't work.
for (var i in arr)
{
strX = str.replace(/i/g, arr[i]);
console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}
Do you guys know how to work around this?
Instead of
strX = str.replace(/i/g, arr[i]);
you want to do something like.
strX = str.replace(new RegExp(i, "g"), arr[i]);
This is because /i/g refers to the letter i, not the value of variable i. HOWEVER one of your base string has plus signs, which is a metacharacter in regexes. These have to be escaped. The quickest hack is as follows:
new RegExp(i.replace(/\+/g, "\\+"), "g"), arr[i]);
Here is a working example: http://jsfiddle.net/mFj2f/
In general, though, one should check for all the metacharacters, I think.
The i in the regex will be the string i, not the variable i. Try instead new RegExp(i,'g'); and you should get the desired results
var W,H,A,K;
W='123456'.split(''),
H='test this WHAK com www for'.split(' '),
A='2 is a 1 (1ed 6 3 2, 1 6 3 that), 1ing 6 5.3.4';
K=0;for(K in W)A=A.split(W[K]).join(H[K]);
document.write(A);

Categories

Resources