Home > database >  How to sort, ignoring any characters that are not numbers
How to sort, ignoring any characters that are not numbers

Time:06-15

I have a sort function that orders items with the class '.sortbox', finds the '.num' value and sorts using flex order. This works fine, but some of the values have extra characters (./-) and this breaks it.

How can I search but ignore all characters that are not numbers?

My attempt here: If I have it all completely wrong then appreciate help to understand why.

https://jsfiddle.net/9cwyund6/1/

function sorting(){
  var items = document.querySelectorAll('.sortbox')
  Array.from(items).sort(function(a, b) {
    a = ~~a.querySelector('.num').innerText
    b = ~~b.querySelector('.num').innerText
    return a - b
  }).forEach(function(n, i) {
    n.style.order = i
  })
}

CodePudding user response:

You could strip the strings a and b from all non digit characters while sorting

return a.replace(/\D/g,'') - b.replace(/\D/g,'')

CodePudding user response:

You can use

isNaN() 

method to check if something is a number or not.

  • Related