Search code examples
javascriptregextokenize

How to split a string into words and numbers?


I need to tokenize a string representing an item in inventory in javascript getting words and numbers, for example:

Given the string 'Plane Engine 50x60' the tokens should be ['Plane','Engine','50','x','60']

Given the string 'Car wheel 220v' the tokens should be ['Car','wheel','220','v']

The solution could be a RegExp or a Javascript Algorithm

All the items have that kind of names come has measures like 20x30 and others have electronic info such as 220v. The thing I need to do is split like the examples above.

Thanks


Solution

  • We can split by groups of either numbers or letters and then filter out the empty strings or spaces.

    'Car wheel 220v'.split(/([0-9]+|[a-zA-Z]+)/).filter(token => (token.match(/[a-zA-Z0-9]/)))