最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I split a string that contains different signs? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Dec 10, 2009 at 12:45 user228720 asked Dec 10, 2009 at 11:20 user228720user228720 1034 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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"]
var myString = word1;word2;word3,word4,word5,word6.word7;
var result = myString.split(/;|,|./);
发布评论

评论列表(0)

  1. 暂无评论