Gordon
Gordon

Reputation: 1651

jquery, text extraction

I have some string like this "asdf_0934_1234 - Pokemons".

How can I extract the strings asdf , 0934 , 1234 and Pokemons? Please note that this is just a sample since the texts can be other characters.

Upvotes: 2

Views: 197

Answers (3)

David Tang
David Tang

Reputation: 93664

If everything will be separated by underscores and dashes, then:

var str = "asdf_0934_1234 - Pokemons";
var strings = str.split(/_|-/);

Then you probably want to trim leading and trailing spaces:

strings = $.map(strings, function (s) {
    return $.trim(s);
});

Upvotes: 5

Herman Schaaf
Herman Schaaf

Reputation: 48425

You can use the javascript split function. Here is the documentation.

In your example:

s = asdf_0934_1234 - Pokemons

I'd first split by the - character:

s.split('-')

to get Pokemons and asdf_0934_1234 and then split the second part again by the _ delimiter to obtain everything you need.

After that, some of the strings might have leading or trailing spaces. So if you have all your results in one array, called tokens, you can get rid of that using:

$.map(tokens, function (s) {
    return $.trim(s);
});

Upvotes: 1

Nick Pyett
Nick Pyett

Reputation: 3408

If the string is of the same format every time, you could use multiple string splits.

str = str.split(" - ");

This will return an array.

http://www.w3schools.com/jsref/jsref_split.asp

Upvotes: 0

Related Questions