1

I run:

var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
    words[i] += " ";
}

And I get an array like:

["27","-","28","August","663","CE"]

How would I iterate with that array and loop it to find if an object is a text string or a number?

rob.m
  • 9,843
  • 19
  • 73
  • 162
  • 3
    look into the [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operator – Patrick Barr Jul 31 '17 at 15:53
  • 2
    That's wrong, you actually get `["27","-","28","August","663","CE"]` – Jeremy Thille Jul 31 '17 at 15:54
  • @JeremyThille you're right, will update the question now – rob.m Jul 31 '17 at 15:55
  • To add one space to each word, you can do `string.split(" ").map(word => word+" " )` – Jeremy Thille Jul 31 '17 at 15:55
  • 5
    @PatrickBarr: Surely they will all be typeof string? – musefan Jul 31 '17 at 15:56
  • ohhh i fell for that trap too @musefan – malifa Jul 31 '17 at 15:57
  • @musefan that was posted before the question was updated with correct types, with jQuery, there's [`jQuery.isNumeric()`](https://api.jquery.com/jQuery.isNumeric/) – Patrick Barr Jul 31 '17 at 15:57
  • what do you want to do? get the numbers only? – Jonas Wilms Jul 31 '17 at 15:57
  • `if (typeof words == "string") { alert("I'm a string!"); }` but would those not be all strings? – rob.m Jul 31 '17 at 15:58
  • @rob.m yes. try to parse them e.g. with parseInt – Jonas Wilms Jul 31 '17 at 15:58
  • or use `isNaN()`. Knowing what you are trying to accomplish I don't see how this array approach will help – charlietfl Jul 31 '17 at 15:58
  • @Jonasw I need to loop all objects and for each of them do a contional, if it is a string.. if it is a number.. – rob.m Jul 31 '17 at 15:58
  • https://stackoverflow.com/a/14794066/2299040 – Sahil Manchanda Jul 31 '17 at 15:59
  • Possible duplicate of [How to check if a variable is an integer in JavaScript?](https://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript) – DarthJDG Jul 31 '17 at 16:00
  • What is really the end goal you want to reach? Probably split is not the fastest way to get there. – trincot Jul 31 '17 at 16:00
  • @trincot I need to loop all objects and for each of them do a contional, if it is a string.. if it is a number.. – rob.m Jul 31 '17 at 16:01
  • What do you want to do further when it is a number, and what when it is a string? What is your final goal? – trincot Jul 31 '17 at 16:02
  • @Maramal must be regex day today, you are like the third one to mention it today – rob.m Jul 31 '17 at 16:02
  • @trincot OP is trying to parse a wide variety of unknown and mixed up date formats https://stackoverflow.com/questions/45417870/how-would-you-handle-different-formats-of-dates – charlietfl Jul 31 '17 at 16:02
  • @charlietfl i saw a pattern on wikipedia, i guess a couple of these parsers would do for most of wikipedia's dates. `22 August 1945 19 May` and `May 4 1945 – August 22 1945` are the most commons – rob.m Jul 31 '17 at 16:04
  • @rob.m they are incredibly helpful in these cases where you can build your own expressions to check explicity what you want. Happy regex day! – Maramal Jul 31 '17 at 16:05
  • How do you want decimal numbers to be treated? What if the value only starts with number(s), like for instance `"24seven"`? – Lennholm Jul 31 '17 at 16:05
  • @MikaelLennholm this is the logic I want to apply: ""If string before white space has `1 number or max 2 numbers` than it' s `a day`, scrap the dash, then check if any string in the whole string match any strings in the year array `"June, July, August.."`, if it does, then it is a `month`, then grab the string after the matching month (we now know it is a month) and consider it as a `year`, if it is not only a number, then consider the last verbal string as a `prefix`. " – rob.m Jul 31 '17 at 16:06
  • NB: a number and a digit are two different concepts. The same holds true for prefix and suffix. – trincot Jul 31 '17 at 16:07
  • @trincot true but (example) `22` by itself cannot be a month or a year, only a day, and take it from that for the rest.. – rob.m Jul 31 '17 at 16:09
  • In the example string you provided in this question, do you want to ignore the 27, and eventually get 28 August 663, or what do you want to happen with that 27? NB: there has been a year 22. – trincot Jul 31 '17 at 16:12
  • @trincot 27 and 28 are days, since they come before August and the eventual year 22, would come after the string August so it'd be a year, at least this is the logic i want to apply to this case – rob.m Jul 31 '17 at 16:17
  • Do you want to ignore any other text that precedes it, or follows it? Or do all characters in your input string relate to the date(s)? – trincot Jul 31 '17 at 16:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150640/discussion-between-rob-m-and-trincot). – rob.m Jul 31 '17 at 16:25
  • @trincot all characters in my input string relate to the date, but now i know which is a number which is, i have also put each one into an array that i can iterate with, so now how can I use `2 August 1945` and `May 4 1945 – April 22 1945` as two basics example to use and say if the new string matches this format do this.. ? – rob.m Jul 31 '17 at 16:44
  • I see you accepted an answer, so I suppose you have your question answered. – trincot Jul 31 '17 at 16:49
  • @trincot yes for the question on here yes, that does the job. What i've quickly asked you tho is different, not sure if I should create a new question, not even sure it is correct, because now I have an array, so i could say if the first object of the array is a number and has 1 or max 2 length is a day etc.. – rob.m Jul 31 '17 at 16:51

6 Answers6

1

To be perfectly correct, these are all of the type string, because they are between quotes. I guess you want to find out if these strings can be converted to a number. You can check this with isNan(), gives false when numeric and true when not. You can actually convert the string to a number (integer) with parseInt();

    var array = ["27","-","28","August","663","CE"];
    for (var el of array) {
      if(!isNaN(el)) {                          // check if el is numeric           
        el = parseInt(el);                      // parse el to a int
        console.log("This element is numeric");
        console.log(el);
      }
    }
Herocaine
  • 109
  • 9
0
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
    console.log(/\d+/g.test(words[i])); // RegExp way (possible only with input formatted like string you specified)
    console.log(/^[\d]+(.[\d]+)*$/g.text(words[i])); // RegExp way that would consider floats, ints as a number and would not consider strings like "123aaa" as a number
    console.log(!isNaN(parseInt(words[i]))); // NaN with parseInt way
    console.log(!isNaN(words[i])); // only NaN way - warning: strings like "123aaa" are considered as a number as parseInt would create an int 

with vale of 123 console.log(!isNan(Number(words[i])) && words[i] !== ''); // csadner's solution with Number // all above logs will output true if the string is a number }

This should probably solve the problem. What's going on here is:

  1. Regular expression checks if provided string contains only the numbers
  2. parseInt will return NaN (Not a Number) on fail, so we check if the returned value is not NaN.
  3. isNaN itself checks if string is a number - in case you don't want to have hexadecimals, etc.
Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70
  • The regex solution doesn't catch negative numbers, decimal points, scientific notation, etc. It also would consider `abc123` a number. I would stick to using `Number()`, `parseInt()`, or `parseFloat()`. – csander Jul 31 '17 at 16:06
  • True, but I was considering the input will only be formatted as the `string` variable specified in question. As you can see there's no way the date will contain numbers, be a float/double or anything else. But true, Number's a nice solution too. – Dawid Zbiński Jul 31 '17 at 16:12
  • Yeah, don't think the OP ever said that all his strings would look like this, so I was just thinking of the general case. But your solutions would definitely work in this case. – csander Jul 31 '17 at 16:15
  • @csander Your points are valid, the same way that `parseInt()` and `parseFloat()` would consider `"123abc"` a number and that `Number()` would consider `""` a number. – Lennholm Jul 31 '17 at 16:16
  • added regexp solution that would consider all the points you had guys, thanks – Dawid Zbiński Jul 31 '17 at 16:20
0

You can use the jQuery $.isNumeric() inside a $.each loop

$.each(words,function(){
    if($.isNumeric(this)) {
        //code to execute if number
    }
})
CumminUp07
  • 1,936
  • 1
  • 8
  • 21
0

In the for loop you already have, you can determine if it's NOT a number with this condition:

!words[i] || isNaN(words[i])

If that is true, it's not a number

Lennholm
  • 7,205
  • 1
  • 21
  • 30
  • @csander Wrong, `isNaN()` tries to parse the string the same way `Number()` does. If that doesn't succeed, it will return `true`. You're thinking of `Number.isNaN()`. – Lennholm Jul 31 '17 at 17:43
0

you can use Number() directly

var arr = ["0","-","28","August","663","CE"]

function isNumber(str) {
  return str && isNaN(Number(str)) ? false : true
}

arr.forEach((item) => {
  console.log(isNumber(item))
})
Kermit
  • 1,062
  • 6
  • 10
  • 0 is a falsy value, so this will consider '0' as non-numeric – csander Jul 31 '17 at 16:09
  • But now the empty string is treated as numeric because it is falsy, so the and condition evaluates to `false` and the function returns `true` – csander Jul 31 '17 at 16:23
0

You can use Number(), which returns NaN if string is non-numeric. One thing to keep in mind is that Number('') === 0.

for (const word of words.split(' ')) {
  if (isNaN(Number(word)) {
    //code if non-numeric
  }
  else {
    //code if numeric
  }
}
csander
  • 1,385
  • 10
  • 11