/    Sign up×
Community /Pin to ProfileBookmark

Multiple split … is it possible

I have not been able to figure out how to do a multiple split.

For example, given:
str = ‘100 + (xvar*3)’;
strArr = str.split(/^w+|^d+|s+/g);
alert(strArr.join(“n”);

I was expecting to see:
100
+
(
xvar
*
3
)

But instead, I get:

+(xvar*3)
which loses the first number altogether and only removes spaces thereafter.

I also tried:
strArr = str.split(/w+|d+|s+/g);
but the display was even less (lost all words and numbers):

+(
*
)

Two questions:
1. Can I split a string on multiple conditions (words, numbers and symbols)?
2. Is there another, or better, way to do it … or is it impossible with a split?

It is my first step in an attempt at trying to convert a statement from ‘infix’ to ‘postfix’.
I just can’t get past the first step
Thanks for any ideas.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@mrhooApr 15.2008 — parenthetise the items you are splitting on to include them in the array-

and use W for punctuation and space characters

[CODE]var str = '100 + (xvar*3)';
strArr = str.split(/(w+|d+|W+)/);
alert(strArr.join("n"));[/CODE]


returned value:

100

  • + (


  • xvar

    *

    3

    )

    If you want each nonword character on its own line, use W instead of W+
    Copy linkTweet thisAlerts:
    @NedalsApr 15.2008 — <i>
    </i>var str = '100+(xvar*3)';
    strArr = str.match(/(w+|d+|W)/g);
    alert(strArr.join("n"));

    Note: I cleared the whitespace before the match.
    Copy linkTweet thisAlerts:
    @JMRKERauthorApr 15.2008 — Thank you 'mrhoo' and 'Nedals'.

    I appreciated the information.
    ×

    Success!

    Help @JMRKER spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...