我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
当前回答
对于那些希望在拆分函数中进行更多自定义的人,我编写了一个递归算法,它使用要拆分的字符列表拆分给定的字符串。在我看到上面的帖子之前,我写了这篇文章。我希望它能帮助一些沮丧的程序员。
splitString = function(string, splitters) {
var list = [string];
for(var i=0, len=splitters.length; i<len; i++) {
traverseList(list, splitters[i], 0);
}
return flatten(list);
}
traverseList = function(list, splitter, index) {
if(list[index]) {
if((list.constructor !== String) && (list[index].constructor === String))
(list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;
(list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;
(list.constructor === Array) ? traverseList(list, splitter, index+1) : null;
}
}
flatten = function(arr) {
return arr.reduce(function(acc, val) {
return acc.concat(val.constructor === Array ? flatten(val) : val);
},[]);
}
var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
splitString(stringToSplit, splitList);
上面的例子返回:["people", "and", "other", "things"]
注:flatten函数取自Rosetta Code
其他回答
一个简单的方法是用每个分隔符处理字符串中的每个字符,并构建一个分隔符数组:
splix = function ()
{
u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0;
for (i = 0; i < u.length; ++i)
{
for (j = 0; j < v.length; ++j)
{
if (u.slice(i, i + v[j].length) == v[j])
{
y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1];
};
};
};
return w;
};
console.logg = function () { document.body.innerHTML += "<br>" + [].slice.call(arguments).join(); } splix = function() { u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0; console.logg("Processing: <code>" + JSON.stringify(w) + "</code>"); for (i = 0; i < u.length; ++i) { for (j = 0; j < v.length; ++j) { console.logg("Processing: <code>[\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]</code>"); if (u.slice(i, i + v[j].length) == v[j]) { y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1]; console.logg("Currently processed: " + JSON.stringify(w) + "\n"); }; }; }; console.logg("Return: <code>" + JSON.stringify(w) + "</code>"); }; setTimeout(function() { console.clear(); splix("1.23--4", ".", "--"); }, 250); @import url("http://fonts.googleapis.com/css?family=Roboto"); body {font: 20px Roboto;}
用法:splix(字符串,分隔符…) 示例:splix("1.23- 4", ".", "——") 返回:["1","23","4"]
a = "a=b,c:d"
array = ['=',',',':'];
for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }
这将返回没有特殊字符的字符串。
传入一个regexp作为参数:
js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!
编辑补充:
你可以通过选择数组的长度减去1来获得最后一个元素:
>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"
... 如果模式不匹配:
>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"
我将为这样的函数提供一个经典的实现。代码可以在几乎所有版本的JavaScript中运行,并且在某种程度上是最优的。
它不使用正则表达式,这很难维护 它没有使用JavaScript的新特性 它不使用需要更多计算机内存的多次.split() .join()调用
只是纯代码:
var text = "Create a function, that will return an array (of string), with the words inside the text";
println(getWords(text));
function getWords(text)
{
let startWord = -1;
let ar = [];
for(let i = 0; i <= text.length; i++)
{
let c = i < text.length ? text[i] : " ";
if (!isSeparator(c) && startWord < 0)
{
startWord = i;
}
if (isSeparator(c) && startWord >= 0)
{
let word = text.substring(startWord, i);
ar.push(word);
startWord = -1;
}
}
return ar;
}
function isSeparator(c)
{
var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
return separators.includes(c);
}
你可以看到代码在playground中运行: https://codeguppy.com/code.html?IJI0E4OGnkyTZnoszAzf
My refactor of @Brian answer var string = 'and this is some kind of information and another text and simple and some egample or red or text'; var separators = ['and', 'or']; function splitMulti(str, separators){ var tempChar = 't3mp'; //prevent short text separator in split down //split by regex e.g. \b(or|and)\b var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g"); str = str.replace(re, tempChar).split(tempChar); // trim & remove empty return str.map(el => el.trim()).filter(el => el.length > 0); } console.log(splitMulti(string, separators))