문제

How do I split a string with multiple separators. (JQuery)

var mystring = "(this is my string!)";

I have tried

var words = mystring.split(/[\s(!)]/);

but it does not work

I wanted to have words (array) content to be
[ ( , this , is , my , string , ! , ) ]

Appreciate all the help. Thanks

도움이 되었습니까?

해결책

split on the characters you choose, and filter the array to remove values that are empty or just spaces (if you don't want them for some reason) ?

var words = (mystring.split(/(\s+|\(|\)|\!)/)).filter(function(n) {return n.trim()});

// returns
// ["(", "this", "is", "my", "string", "!", ")"] 

FIDDLE

다른 팁

You could do something like this:

mystring.replace( '(', '( ' ).replace( ')', ' )' ).split( ' ' );

However, it really depends on what pattern you expect your input to match. You need to ask yourself questions like, does all of my input start and end with parenthesis? etc...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top