Skip to content Skip to sidebar Skip to footer

Split Characters And Numbers From A String To Array Javascript

I have a scenario in which i have to separate the numbers and characters in a single line of string Example const a = '30000kg , 400lbs'; const output_expected = ['30000','kg','400

Solution 1:

try this:

const reg = /([0-9.]+)(?![0-9.])|([a-z]+)(?![a-z])/gi

console.log("30000kg , 400lbs".match(reg)); // --> [ "30000", "kg", "400", "lbs" ]
console.log("30,000kg , 400lbs".match(reg)); // --> [ "30", "000", "kg", "400", "lbs" ]
console.log("30.000kg,400lbs".match(reg)); // --> [ "30.000", "kg", "400", "lbs" ]
console.log("30.000KG.400LBS".match(reg)); // --> [ "30.000", "KG", ".400", "LBS" ]

alternatively, if you want to trim the '.' in case 4

const reg = /(?:[^.]([0-9.]+)(?![0-9.]))|(?:([a-z]+)(?![a-z]))/gi

console.log("30.000KG.400LBS".match(reg)); // --> [ "30.000", "KG", "400", "LBS" ]

Solution 2:

A good opportunity for you to learn something about formal grammars and parsing. Here's an example to get you started:

GRAMMAR = String.raw`

  String = a:Item b:(_ "," _ Item)*  {
    return [a].concat(b.map(i => i.pop()))
  }

  Item = n:Number _ u:Unit {
    return  {n, u}
  }

  Number = a:Int b:(Separator? Int)* {
    return a + b.map(i => i.pop())
  }

  Int = a:[0-9]+ {
    return a.join('')   
  }

  Separator = "," / "."

  Unit = "kg" / "KG" / "lbs" / "LBS"

  _ = [ \t\n\r]*
`PARSER = PEG.buildParser(GRAMMAR)

test = [
"30000kg , 400lbs",
"30,000kg , 400lbs",
"30.000kg,400lbs",
"30.000KG.400LBS"
]

for (t of test)
  console.log(PARSER.parse(t))
  
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/pegjs/0.9.0/peg.js"></script>

See https://pegjs.org/ for more info and docs.

Solution 3:

splitWeights = (weights) => {
    const weightRegex = newRegExp('(\\d+(?:.|,)?\\d+)(lbs|kg)', 'g');
    const matches = [...weights.matchAll(weightRegex)];

  const result = [];
  matches.forEach(m => {
    result.push(m[1]);
    result.push(m[2]);
  });
  return result;
}

console.log(splitWeights("30000kg , 400lbs"));

Post a Comment for "Split Characters And Numbers From A String To Array Javascript"