views:

89

answers:

2

I want to split a string that can look like this: word1;word2;word3,word4,word5,word6.word7. etc.

The string is from an output that I get from a php page that collects data from a database so the string may look different but the first words are always separated with ; and then , and the last words with .(dot)

I want to be able to fetch all the words that ends with for example ; , or . into an array. Does someone know how to do this?

I would also like to know how to fetch only the words that ends with ;

The function ends_with(string, character) below works but it takes no regard to whitespace. For example if the word is Jonas Sand, it only prints Sand. Anybody knows how to fix this?

+6  A: 

Probably

var string = "word1;word2;word3,word4,word5,word6.word7";
var array = string.split(/[;,.]/);
// array = ["word1", "word2", "word3", "word4", "word5", "word6", "word7"]

The key is in the regular expression passed to the String#split method. The character class operator [] allows the regular expression to select between the characters contained with it.

If you need to split on a string that contains more than one character, you can use the | to differentiate.

var array = string.split(/;|,|./) // same as above

Edit: Didn't thoroughly read the question. Something like this

var string = "word1;word2;word3,word4,word5,word6.word7";

function ends_with(string, character) {
  var regexp = new RegExp('\\w+' + character, 'g');
  var matches = string.match(regexp);
  var replacer = new RegExp(character + '$');
  return matches.map(function(ee) {
    return ee.replace(replacer, '');
  });
}
// ends_with(string, ';') => ["word1", "word2"]
jonchang
But if I just want the words that end with ;
nice!! this works perfectly... Thanks!
Still get problems when for exampel word3 have whitespace like ;James,Jonas Sand, the code only prints out Howard,Sand
I mean James,Sand
A: 
var myString = word1;word2;word3,word4,word5,word6.word7;
var result = myString.split(/;|,|./);
Pieter888