Question

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?

Was it helpful?

Solution

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"]

OTHER TIPS

var myString = word1;word2;word3,word4,word5,word6.word7;
var result = myString.split(/;|,|./);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top