Steeve17
Steeve17

Reputation: 492

Splitting a string using a regexp that matches more than one character

I am trying to achieve the following for both @ or #.

function split(val) {
    return val.split(/@/);
}

function extractLast(term) {
    return split(term).pop();
}

Any help really appreciated!

Upvotes: 1

Views: 152

Answers (2)

El Ronnoco
El Ronnoco

Reputation: 11922

Try

val.split(/@|#/g);

The | is the regex alternation operator ie 'OR'. The g flag makes the expression match globally (ie all instances)

See this fiddle

As Pointy notes the g flag isn't necessary here. It is however necessary if wanting to find all matches within a string in JS regular expressions.

Upvotes: 7

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

you could do

function split(val) {
    return val.split(/[@#]/g);
}

Upvotes: 2

Related Questions