我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
当前回答
让我们保持简单:(在你的RegEx中添加“[]+”表示“1或更多”)
这意味着“+”和“{1,}”是相同的。
var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept
其他回答
我发现我需要这样做的主要原因之一是在/和\上拆分文件路径。这是一个有点棘手的正则表达式,所以我将它贴在这里作为参考:
var splitFilePath = filePath.split(/[\/\\]/);
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))
您可以将所有想要单独或共同用作分隔符的字符合并到一个正则表达式中,并将它们传递给split函数。例如,你可以这样写:
console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );
输出将是:
["dasdnk", "asd", "naks", ":d", "skldma"]
例如,如果你在String 07:05:45PM中使用了split and replace
var hour = time.replace("PM", "").split(":");
结果
[ '07', '05', '45' ]
我认为如果你指定你想要保留什么,而不是你想要删除什么,会更容易。
如果你只想要英语单词,你可以这样用:
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>