简体   繁体   English

在特定字符处分割字符串

[英]Split String at specific character

I have the following code: 我有以下代码:

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

The function takes no regard to whitespace. 该功能不考虑空格。 For example if you input 例如,如果您输入

ends_with('Jonas Sand,', ',')

the output will be Sand. 输出将是Sand。 Need help on making the function work with words that has whitespace. 在使函数与带有空格的单词一起使用时需要帮助。

You can use your separator within split and take all except the last part with slice : 您可以在split使用分隔符,并使用slice除最后一部分以外的所有内容:

function ends_with(string, character) {
    return string.split(character).slice(0, -1);
}

\\w matches word characters, use [^x] instead, where x is your character. \\w匹配单词字符,请改用[^x] ,其中x是您的字符。 This matches everything but your character. 除了你的角色,这一切都匹配。

So the first line in your function becomes 因此,函数的第一行变为

var regexp = new RegExp('[^' + character + "]+" + character, 'g');

on the other hand, if you want to match words separated by white space, use 另一方面,如果要匹配用空格隔开的单词,请使用

var regexp = new RegExp('(\\w|\\s)+" + character, 'g');

PS: but isn't there a String#split function in javascript? PS: 但是JavaScript中没有String#split函数吗?

尝试使用'[\\\\w\\\\s]+'而不是'\\\\w+'来包含空格。

Try the following: 请尝试以下操作:

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

function ends_with(string, character) {
    var regexp = new RegExp('.+' + character, 'g');
    var matches = string.match(regexp);
    var replacer = new RegExp(character + '$');
    return matches.map(function(ee) {
        return ee.replace(replacer, '');
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM