[英]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.
在使函数与带有空格的单词一起使用时需要帮助。
\\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.