开发者

Numbers from string with javascript

开发者 https://www.devze.com 2023-02-16 21:24 出处:网络
candy 5.5, icecream 3.4, something valuable 1,185.5*2 Im using . and , for separators specifically. im need to get from this string
candy 5.5, icecream 3.4, something valuable 1,185.5*2

Im using . and , for separators specifically. im need to get from this string

var sum = 5.5 + 3.4 + 1185.5*2

开发者_如何学C


My choice would be this:

var buildSumString = function(testString) {
    rx=/(\d[\d\.\*]*)/g
    return 'var sum = ' + testString.match(rx).join(' + ');
};

var testString = "candy 5.5, icecream 3.4, something valuable 1,185.5*2";
var rebuiltString = buildSumString(testString);

The only assumption to make here is that there will be no white space in your number strings, though that can be easily added.


I am quite sure this could be implemented using regular expressions

Using a pattern like

(?:([0-9.,*]+).*?)?

to find all occurrences (in java-script i think it is the g modifier) and then just some standard processing to remove all of the commas and then add the fields as usual

If you haven't used regular expressions before W3schools is usually a good place to start http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Sorry i cant give anything more specific but i haven't used javascript enough


Poor design because you have a comma as a separator and also as a part of a number.

My advice is to make two passes through the string. First look for , between two digits followed by 3 digits, and delete the commas. Regular expresssions might be useful here. On the swecond pas split the string on the commas, then on each part scan from the right to the first space character to break off the numeric parts.

Build a string by adding plus signs, and then use eval to do the calculation. That will take care of any extra multiply operations.


You can get an expression string from your string like this[*]:

 var str = 'candy 5.5, icecream 3.4, something valuable 1,185.5*2'
   , sum = str.replace(/[a-z]+|,\s+/gi,'').trim().split(/\s+/).join(' + ');

and eval it. Still, you may want to think about other ideas to handle this (using a better separator in the initial string, a way to avoid eval (considered evil) etc.)

[*] trim being

String.prototype.trim = function(){
 return this.replace(/^\s+|\s+$/,'');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消