如何在JavaScript中使用多个分隔符拆分字符串? 我正在尝试在逗号和空格上进行拆分,但是AFAIK,JS的拆分功能仅支持一个分隔符。


#1楼

对于那些想要在拆分功能中进行更多自定义的人,我编写了一个递归算法,该算法将给定的字符串与要拆分的字符列表进行拆分。 我在看到以上帖子之前就写了这篇文章。 我希望它可以帮助一些沮丧的程序员。

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


#2楼

棘手的方法:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]

#3楼

您可以将要用作分隔符的所有字符单独或共同打包成正则表达式,然后将它们传递给split函数。 例如,您可以编写:

console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );

输出将是:

["dasdnk", "asd", "naks", ":d", "skldma"]

#4楼

我不知道RegEx的性能,但这是RegEx的另一种选择,它利用本机HashSet并以O(max(str.length,delimeter.length))复杂性工作:

var multiSplit = function(str,delimiter){if (!(delimiter instanceof Array))return str.split(delimiter);if (!delimiter || delimiter.length == 0)return [str];var hashSet = new Set(delimiter);if (hashSet.has(""))return str.split("");var lastIndex = 0;var result = [];for(var i = 0;i<str.length;i++){if (hashSet.has(str[i])){result.push(str.substring(lastIndex,i));lastIndex = i+1;}}result.push(str.substring(lastIndex));return result;
}multiSplit('1,2,3.4.5.6 7 8 9',[',','.',' ']);
// Output: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]multiSplit('1,2,3.4.5.6 7 8 9',' ');
// Output: ["1,2,3.4.5.6", "7", "8", "9"]

#5楼

我使用regexp:

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';var strNew = str.match(/\w+/g);// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

#6楼

我发现我需要这样做的主要原因之一是在/\\上拆分文件路径。 这是一个棘手的正则表达式,所以我将其发布在这里以供参考:

var splitFilePath = filePath.split(/[\/\\]/);

#7楼

我认为,如果您指定要离开的内容而不是要删除的内容,会更容易。

好像您只想使用英语单词一样,可以使用以下形式:

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> 

#8楼

让我们保持简单:(在RegEx中添加“ [] +”表示“ 1或更多”)

这意味着“ +”和“ {1,}”相同。

var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept

#9楼

从@ stephen-sweriduk解决方案(对我来说更有趣!)开始,我对其进行了少许修改,以使其更加通用和可重用:

/*** Adapted from: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
*/
var StringUtils = {/*** Flatten a list of strings* http://rosettacode.org/wiki/Flatten_a_list*/flatten : function(arr) {var self=this;return arr.reduce(function(acc, val) {return acc.concat(val.constructor === Array ? self.flatten(val) : val);},[]);},/*** Recursively Traverse a list and apply a function to each item* @param list array* @param expression Expression to use in func* @param func function of (item,expression) to apply expression to item**/traverseListFunc : function(list, expression, index, func) {var self=this;if(list[index]) {if((list.constructor !== String) && (list[index].constructor === String))(list[index] != func(list[index], expression)) ? list[index] = func(list[index], expression) : null;(list[index].constructor === Array) ? self.traverseListFunc(list[index], expression, 0, func) : null;(list.constructor === Array) ? self.traverseListFunc(list, expression, index+1, func) : null;}},/*** Recursively map function to string* @param string* @param expression Expression to apply to func* @param function of (item, expressions[i])*/mapFuncToString : function(string, expressions, func) {var self=this;var list = [string];for(var i=0, len=expressions.length; i<len; i++) {self.traverseListFunc(list, expressions[i], 0, func);}return self.flatten(list);},/*** Split a string* @param splitters Array of characters to apply the split*/splitString : function(string, splitters) {return this.mapFuncToString(string, splitters, function(item, expression) {return item.split(expression);})},}

接着

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
var splittedString=StringUtils.splitString(stringToSplit, splitList);
console.log(splitList, stringToSplit, splittedString);

返回原样:

[ ' ', '_', '/' ] 'people and_other/things' [ 'people', 'and', 'other', 'things' ]

#10楼

嗨,例如,如果您已在字符串07:05:45 PM中拆分并替换了字符串

var hour = time.replace("PM", "").split(":");

结果

[ '07', '05', '45' ]

#11楼

另一个简单但有效的方法是重复使用split + join。

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

本质上,先进行拆分再进行联接,就像全局替换一样,因此这将每个分隔符替换为逗号,然后在替换所有分隔符后对逗号进行最终拆分

上面表达式的结果是:

['a', 'b', 'c', 'd']

对此进行扩展,您还可以将其放置在函数中:

function splitMulti(str, tokens){var tempChar = tokens[0]; // We can use the first token as a temporary join characterfor(var i = 1; i < tokens.length; i++){str = str.split(tokens[i]).join(tempChar);}str = str.split(tempChar);return str;
}

用法:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

如果您经常使用此功能,则可能甚至值得考虑将String.prototype.split包裹起来以方便使用(我认为我的功能相当安全-唯一的考虑是条件(额外)的额外开销,以及它缺少一个limit参数的实现(如果传递了数组)。

如果对下面的方法使用这种方法,请确保包括splitMulti函数:)。 还值得一提的是,有些人不愿扩展内置函数(因为很多人做错了,可能会发生冲突),因此如果有疑问,请在使用此函数之前先与更高级的人谈谈或询问:)

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fnString.prototype.split = function (){if(arguments[0].length > 0){if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an arrayreturn splitMulti(this, arguments[0]);  // Call splitMulti}}return splitOrig.apply(this, arguments); // Call original split maintaining context};

用法:

var a = "a=b,c:d";a.split(['=', ',', ':']); // ["a", "b", "c", "d"]// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)a.split('='); // ["a", "b,c:d"]

请享用!


#12楼

一种简单的方法是使用每个定界符处理字符串的每个字符并构建拆分数组:

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(string, delimiters...)

示例: splix("1.23--4", ".", "--")

返回: ["1", "23", "4"]


#13楼

这不是最佳方法,但是可以使用多个不同的分隔符/分隔符进行拆分

html

<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>

javascript

<script>
function myFunction() {var str = "How : are | you doing : today?";
var res = str.split(' | ');var str2 = '';
var i;
for (i = 0; i < res.length; i++) { str2 += res[i];if (i != res.length-1) {str2 += ",";}
}
var res2 = str2.split(' : ');//you can add countless options (with or without space)document.getElementById("demo").innerHTML = res2;
</script>

#14楼

a = "a=b,c:d"array = ['=',',',':'];for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }

这将返回没有特殊字符的字符串。


#15楼

这是在ES6中实现相同目标的新方法:

 function SplitByString(source, splitBy) { var splitter = splitBy.split(''); splitter.push([source]); //Push initial value return splitter.reduceRight(function(accumulator, curValue) { var k = []; accumulator.forEach(v => k = [...k, ...v.split(curValue)]); return k; }); } var source = "abc,def#hijk*lmn,opq#rst*uvw,xyz"; var splitBy = ",*#"; console.log(SplitByString(source, splitBy)); 

请注意此功能:

  • 不涉及正则表达式
  • 按与source出现的顺序返回拆分值

以上代码的结果将是:


#16楼

我将提供此类功能的经典实现。 该代码几乎可以在所有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);
}

您可以看到在操场上运行的代码: https : //codeguppy.com/code.html?IJI0E4OGnkyTZnoszAzf


#17楼

我对@Brian答案的重构

 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 eg \\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)) 

#18楼

也许您应该执行某种字符串替换操作,以将一个分隔符转换为另一个分隔符,这样您的拆分中就只能处理一个分隔符。


#19楼

您可以将正则表达式传递给Javascript的split运算符 。 例如:

"1,2 3".split(/,| /)
["1", "2", "3"]

或者,如果您希望允许多个分隔符一起仅充当一个分隔符:

"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]

(您必须使用非捕获(?:)括号,因为否则它会被拼接回结果中。或者您可以像Aaron一样聪明,并使用字符类。)

(示例在Safari + FF中测试)


#20楼

传递正则表达式作为参数:

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中使用多个分隔符分割字符串?相关推荐

  1. 如何在JavaScript中实现链接列表

    If you are learning data structures, a linked list is one data structure you should know. If you do ...

  2. regexp 好汉字符串_如何在JavaScript中使用RegExp确认字符串的结尾

    regexp 好汉字符串 by Catherine Vassant (aka Codingk8) 由凯瑟琳·瓦森(Catherine Vassant)(又名Codingk8) 如何在JavaScrip ...

  3. !! javascript_产量! 产量! 生成器如何在JavaScript中工作。

    !! javascript by Ashay Mandwarya ?️?? 由Ashay Mandwarya提供吗? 产量! 产量! 生成器如何在JavaScript中工作. (Yield! Yiel ...

  4. javascript案例_如何在JavaScript中使用增强现实-一个案例研究

    javascript案例 by Apurav Chauhan 通过Apurav Chauhan 如何在JavaScript中使用增强现实-一个案例研究 (How to use Augmented Re ...

  5. java+script+当前日期_如何在JavaScript中获取当前日期?

    如何在JavaScript中获取当前日期? #1楼 您可以使用扩展了 Date对象的Date.js库,从而可以使用.today()方法. #2楼 如果您想对日期格式进行更多的粒度控制,我强烈建议您查看 ...

  6. 如何在Javascript中访问对象的第一个属性?

    本文翻译自:How to access the first property of an object in Javascript? Is there an elegant way to access ...

  7. 如何在JavaScript中实现堆栈和队列?

    本文翻译自:How do you implement a Stack and a Queue in JavaScript? What is the best way to implement a St ...

  8. 如何在JavaScript中比较数组?

    本文翻译自:How to compare arrays in JavaScript? I'd like to compare two arrays... ideally, efficiently. 我 ...

  9. 如何在JavaScript中验证电子邮件地址

    如何在JavaScript中验证电子邮件地址? #1楼 与squirtle相比 ,这是一个复杂的解决方案,但是在正确验证电子邮件方面做得非常出色: function isEmail(email) { ...

最新文章

  1. 区块链BaaS云服务(21)腾讯CCGP跨链平台“系统架构”
  2. mysql中的逻辑类型如何定义_MYSQL存储过程即常用逻辑知识点总结
  3. Makefile 学习 1
  4. 本人开源项目 Lu-Rpc
  5. Django从理论到实战(part2)--virtualenvwrapper
  6. HTML与CSS基础之兄弟元素(六)
  7. 高斯金字塔 拉普拉斯金字塔_金字塔学入门指南
  8. linux 文件系统 簇 浪费空间,Linux rm -rf删除文件不释放空间的解决办法
  9. 抖音发布2020数据报告:日均视频搜索量破4亿,70后最爱发表情包
  10. 异构广告混排在美团到店业务的探索与实践
  11. request,response,session
  12. java常见基础面试题
  13. LintCode_408 二进制求和
  14. 时间字符串以及时间戳解析
  15. 雷达信号处理读书笔记
  16. 64位系统和32位系统区别
  17. 《python网络数据采集》读书笔记
  18. mongoose用模型更新不了,因为模型对象中默认带有_id会提示errmsg: “Performing an update on the path ‘_id‘ would modify the i
  19. [转载]VBA创建数据透视表
  20. Blog UPUP——域名、图床与其他

热门文章

  1. OpenGL鼠标拾取
  2. 你有没有想过你的上级为什么让你干这件事情,他想干什么
  3. Android stadio
  4. Android10.0 Binder通信原理(七)-Framework binder示例
  5. LeetCode 6 Z字形变换
  6. JavaScript中函数文档注释
  7. JS数组去重的6种算法实现
  8. A Horrible Poem(bzoj 2795)
  9. 今日课堂学习笔记01
  10. 深入理解javascript的闭包