How do I check if a string is of the form 10*10*10 using Javascript/JQuery and then do math

I'm trying to dynamically calculate volume based on the input of some carton dimensions.

e.g a For a carton with dimensions 10cm x 10cm x 10cm the user inputs 10*10*10 into a text input.

My javascript will then check to see if the input matches this pattern and do the math and populate another input with the result. 10 x 10 x 10 = 1000.

I think I need to use Regular Expressions which I don't have much experience with. The code below stops working at the match stage.(Invalid regular expression: /d+*d+*d+/: Nothing to repeat) Although I'm pretty sure I don't know what I'm doing after that.

Can anyone help?


var pattern = "(\d+)\*(\d+)\*(\d+)";    
var result = carton_dimensions.match(pattern); 





First, the pattern is worngly declared, it should be without " but /:

var pattern = /(\d+)\*(\d+)\*(\d+)/; 

Also, the results you are looking for are in the indexes 1,2 and 3:

volume = result[1] * result[2] * result[3];

So, your final code must something like this:

carton_dimensions = $("input").val();

var pattern = /(\d+)\*(\d+)\*(\d+)/;    
var result = carton_dimensions.match(pattern); 

    volume = result[1] * result[2] * result[3];

Here is a JSFiddle with a working example.

^                   ^

is a string literal. What you need is a regex literal:

^                   ^

Alternatively you can use the RegExp constructor, but then you have to deal with escaping special characters within the string literal so the value is equivalent to the regular expression that you intend to use:

new RegExp("(\\d+)\\*(\\d+)\\*(\\d+)")

For the calculation, you can use javascript's eval like this:

var answer = eval(result[0] + '*' + result[1] + '*' + result[2]);

And since you are validating the input, you should be safe.

Need Your Help

Import from Team Foundation Server 2005 into 2008

tfs import tfs2008 tfs2005

We have an existing TFS 2005 install and a newer 2008. The 2008 server already has some newer projects on it but I am looking to move the older projects from 2005 onto this newer server.

Github pages hosted jekyll blog post loop not showing but pages are working

github jekyll github-pages

I created a jekyll blog on my computer and it's working pretty fine on localhost:4000. and then I created a github pages repo like then I uploaded my local jekyll site using git...