[removed] Split a string into array matching parameters

前端 未结 3 1691
陌清茗
陌清茗 2021-01-07 06:39

I have a string that has numbers and math operators (+,x,-, /) mixed in it

\'12+345x6/789\'

3条回答
  •  滥情空心
    2021-01-07 07:37

    If you are unconcerned with whitespace, all you need is

    '12+345x6/78-9'.match(/\d+|[\+-\/x]/g);
    

    which splits the string into numbers and the +, -, \, and x tokens.

    'use strict';
    const tokens = '12+345x6/78-9'.match(/\d+|[\+-\/x]/g);
    
    console.log(tokens);

    To handle whitespace, consider

    '12+3 45 x6/78-9'.match(/\d|\d[\s\d]\d|[\+-\/x]/g);
    

    which splits the string into numbers (optionally allowing whitespace as a digit separator within a single number) and +, -, \, and x.

    'use strict';
    const tokens = '12+3 45 x6/78-9'.match(/\d+\s?\d+|\d+|[\+-\/x]/g);
    
    
    console.log(tokens);

提交回复
热议问题