我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
当前回答
例如,如果你在String 07:05:45PM中使用了split and replace
var hour = time.replace("PM", "").split(":");
结果
[ '07', '05', '45' ]
其他回答
让我们保持简单:(在你的RegEx中添加“[]+”表示“1或更多”)
这意味着“+”和“{1,}”是相同的。
var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept
我认为如果你指定你想要保留什么,而不是你想要删除什么,会更容易。
如果你只想要英语单词,你可以这样用:
text.match(/[a-z'\-]+/gi);
示例(运行片段):
var R=[/[a-z'\-]+/gi,/[a-z'\-\s]+/gi]; var s=document.getElementById('s'); for(var i=0;i<R.length;i++) { var o=document.createElement('option'); o.innerText=R[i]+''; o.value=i; s.appendChild(o); } var t=document.getElementById('t'); var r=document.getElementById('r'); s.onchange=function() { r.innerHTML=''; var x=s.value; if((x>=0)&&(x<R.length)) x=t.value.match(R[x]); for(i=0;i<x.length;i++) { var li=document.createElement('li'); li.innerText=x[i]; r.appendChild(li); } } <textarea id="t" style="width:70%;height:12em">even, test; spider-man But saying o'er what I have said before: My child is yet a stranger in the world; She hath not seen the change of fourteen years, Let two more summers wither in their pride, Ere we may think her ripe to be a bride. —Shakespeare, William. The Tragedy of Romeo and Juliet</textarea> <p><select id="s"> <option selected>Select a regular expression</option> <!-- option value="1">/[a-z'\-]+/gi</option> <option value="2">/[a-z'\-\s]+/gi</option --> </select></p> <ol id="r" style="display:block;width:auto;border:1px inner;overflow:scroll;height:8em;max-height:10em;"></ol> </div>
你可以将一个正则表达式传递给JavaScript的split()方法。例如:
"1,2 3".split(/,| /)
["1", "2", "3"]
或者,如果你想让多个分隔符一起只起到一个作用:
"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]
您必须使用非捕获(?:)括号,因为 否则它会被拼接回结果中。或者你可以聪明一点 比如Aaron,使用一个角色类。
在Safari和Firefox中测试的示例。
我很惊讶没有人建议它,但我的hack-ey(疯狂的快速)解决方案是附加几个“替换”调用之前由相同的字符分裂。
即删除a, b, c, d和e:
let str = 'afgbfgcfgdfgefg'
let array = str.replace('a','d').replace('b','d').replace('c','d').replace('e','d').split('d')
这可以方便地概括为一个拆分器数组,如下:
function splitByMany( manyArgs, string ) {
do {
let arg = manyArgs.pop()
string = string.replace(arg, manyArgs[0])
} while (manyArgs.length > 2)
return string.split(manyArgs[0])
}
因此,在您的情况下,您可以调用
let array = splitByMany([" ", ","], 'My long string containing commas, and spaces, and more commas');
在Github上查看我的简单库
如果你真的不想访问或与repo交互,下面是工作代码:
/**
*
* @param {type} input The string input to be split
* @param {type} includeTokensInOutput If true, the tokens are retained in the splitted output.
* @param {type} tokens The tokens to be employed in splitting the original string.
* @returns {Scanner}
*/
function Scanner(input, includeTokensInOutput, tokens) {
this.input = input;
this.includeTokensInOutput = includeTokensInOutput;
this.tokens = tokens;
}
Scanner.prototype.scan = function () {
var inp = this.input;
var parse = [];
this.tokens.sort(function (a, b) {
return b.length - a.length; //ASC, For Descending order use: b - a
});
for (var i = 0; i < inp.length; i++) {
for (var j = 0; j < this.tokens.length; j++) {
var token = this.tokens[j];
var len = token.length;
if (len > 0 && i + len <= inp.length) {
var portion = inp.substring(i, i + len);
if (portion === token) {
if (i !== 0) {//avoid empty spaces
parse[parse.length] = inp.substring(0, i);
}
if (this.includeTokensInOutput) {
parse[parse.length] = token;
}
inp = inp.substring(i + len);
i = -1;
break;
}
}
}
}
if (inp.length > 0) {
parse[parse.length] = inp;
}
return parse;
};
用法很简单:
var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", false , new Array('+','-')).scan();
console.log(tokens);
给:
['ABC', 'DE', 'GHIJK', 'LMNOP']
如果您希望在输出中包含分隔令牌(+和-),将false设置为true,瞧!它仍然有效。
现在的用法是:
var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", true , new Array('+','-')).scan();
and
console.log(tokens);
将:
['ABC', '+', 'DE', '-', 'GHIJK', '+', 'LMNOP']
享受吧!