I have a string which I need to split into an array and then perform mathematical functions on each element of the array.
Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!
var stringBits = theString.split('/');
var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);
What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.
An easier method is to map to the Number object
result= stringBits.map(Number);
javascript 1.6. has map() ( https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map ), so you can do something like
intArray = someArray.map(function(e) { return parseInt(e) })
You can just loop through it:
for(var i = 0; i < stringBits.length; i++) {
stringBits[i] = parseInt(stringBits[i]);
}
["1","2"].map(Number)
result: [1,2]
If you add a plus (+) sign in front of your strings they should be converted to numeric.
For example, this will print 3:
var x = "1";
var y = "2";
alert((+x) + (+y));
But I am not sure if this is portable to all browsers.
Your code will become:
var stringBits = theString.split('/');
var result = (+stringBits[0]) + (+stringBits[3]) / (+stringBits[1]);
But this is just a hack, so use with care.
I think the parseInt states better what you are trying to do, but you should delegate this responsibility to another method that returns the final data that you need to process. Convert and then process, don’t convert while processing. Your code will be easier to read.
Related
I have looked at many of the posts involving this kind of question but I have not been able to find anything that works in this situation.
I have a variable x, it is an integer given the following value.
let x = Math.ceil(Math.sqrt(characterNumber));
My goal is to segment a string into array elements of the desired length. Using integers I can do so like the following.
let secondMessage = newMessage.match(/.{1,3}/g);
My ideal solution would be for the following to work, however whatever I am trying returns as null. In my code editor, when I pass anything that is not an integer (x in this case) the colour of the inside {} changes.
let secondMessage = newMessage.match(/.{1,x}/g);
I have tried creating a RegExp, however that also returns null.
Thank you for any answers and sorry for the long (possibly repeated) question.
Variables aren't expanded inside regular expressions. You need to construct the regular expression dynamically by creating a string and then calling new RegExp().
let x = 3;
let rx = new RegExp(`.{1,${x}}`, 'g');
let newMessage = 'abcdefghij';
let secondMessage = newMessage.match(rx);
console.log(secondMessage);
I have a two dimensional array which consists of versions like,
say,
var version = [[B2.0.2.1],[B3.0.2.1], and many more];
How do I split B from these versions because I am only interested in the version that is 2.0.2.1 and so on?
The slice method will be useful in solving your problem.
Here is an example:
var str = "B2.0.2.1";
var res = str.slice(1); // Will result in second character until the end.
// res = "2.0.2.1"
If you use it with a single parameter str.slice(1); you will effectively cut off the first character leaving you with just the version number.. This is assuming that only one letter ever prefixes the versions numbers.
Use array.map to manipulate each element in array
var version = [['B2.0.2.1'],['B3.0.2.1']];
version = version.map(function(ver){
return [ver[0].slice(1)];
});
The simplest way, without loops is using JSON methods
var stripped = JSON.parse(JSON.stringify(version).replace(/B/g, ''));
console.log(stripped);
In this case, I don't even care that your original code is invalid javascript, nor what you'd need to do to fix it, this will get rid of all B's regardless
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']
I have a DIV that is fed by a server side script that I don't have access too, and it outputs the value in £'s.
HTML Example:
<div id="totalExpenditure">£1,125</div>
I then want to have a jQuery script take that figure and workout the difference between a set value of £2,000 and result it to another DIV.
Which says: <div id="totalSurplus">You have £725 remaining.</div>
I've searched Google for mathmatic jQuery but the results look far too complex. What I'm not sure is even possible is to convert the output of the ID totalExpenditure into the DOM to be manipulated.
1) get the string: var myVal = $('#totalExpenditure').text()
2) Get rid of the non-numeric pound sign: myVal = myVal.replace('£','') and the comma myVal = myVal.replace(',','')
3) turn it into an number: myVal = parseFloat(myVal)
4) Perform any math you want with myVal.
You can do this all in one step, but this gives you an idea of how the language works.
You've got two issues here.
First you need to parse a string and convert it to a number.
Then you need to perform the calculation.
Neither of these are really jquery specific. JQuery can help with getting the string, and writing the output, but the rest is just pure javascript.
var num = parseFloat($("#totalExpenditure").text().replace("£", ""));
var remain = 2000 - num;
var outputStr = "You have £" + remain.toFixed(2) + " remaining";
$("#totalSurplus").text(outputStr);
For more control over the output of the currency perhaps check out this post: How can I format numbers as money in JavaScript?
You are able to feed the value (£1,125) from the server to the client's JavaScript engine the same way you're feeding HTML to the client.
It is really not recommended to read a DOM element for a text node and interpret said node as a value for mathematical operations. You should have a JavaScript variable aside to calculate this for you.
obtain the totalExpenditure div content and set totalExpenditure var value (using a regex):
var content = $('#totalExpenditure').text();
var pattern = /[0-9\.,]/g;
var totalExpenditure = pattern.exec(content);
subtract
var totalImport = 2000;
var result = totalImport - totalExpenditure;
I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.
So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
if(assoc["dr"] === undefined ) {
// not found. todo: replace
}
I'd really appricate any help! Is there any simpler way of doing this using JQuery?
Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.
You appear to be misusing for...in.
Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.