简体   繁体   English

我如何使用正则表达式在不是字符的所有内容上拆分字符串

[英]How can I use regex to split a string on everything that is not a character

How could I use vanilla javascript and regex to split on every character that is not a string? 如何使用香草javascript和正则表达式对不是字符串的每个字符进行拆分? Example: 例:

var src = "wer%55";

and have it return the array as 并将其返回为

"wer","%","55"

Thanks! 谢谢!

You can use /(\\W+)/ for splitting and make sure to group \\W+ (1+ non-word characters) to be able to return it in the resulting array: 您可以使用/(\\W+)/进行拆分,并确保将\\W+ (1个非单词字符)分组,以便能够在结果数组中返回它:

 var src = "wer%55"; console.log(src.split(/(\\W+)/)); // add filter(Boolean) to discard empty values from result array src = "wer%55#"; console.log(src.split(/(\\W+)/)); console.log(src.split(/(\\W+)/).filter(Boolean)); 

Split the string by the word boundary \\b : 用单词\\b分隔字符串:

 var src = "wer%55$$abc33"; console.log(src.split(/\\b/)); 

Or 要么

Use String#match to get sequences of word / non word characters: 使用String#match获得单词/非单词字符的序列:

 var src = "wer%55$$abc33"; console.log(src.match(/\\w+|\\W+/g)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用正则表达式和jQuery匹配字符集中不存在的所有内容? - How can I match everything not in a character set with regex and jQuery? 如何使用 JavaScript 正则表达式拆分字符串? - How can I split a string with a JavaScript regex? 我可以使用正则表达式作为String.split()的分隔符吗? - Can I use a regex for the delimiter for String.split()? 如何使用正则表达式拆分字母和数字上的字符串和数字后跟数字 - How Can I Use Regex To Split A String on Letters and Numbers and Carets followed by digits 如何在 JS 中将字符串拆分为 2 个字符块的数组? - How can I split a string into an array of 2 character blocks in JS? 如何在不丢失分隔符和正则表达式的情况下拆分字符串? - How can I split a string without losing the separator and without regex? 如何在正则表达式 String.split() 中包含分隔符? - How can I include the delimiter with regex String.split()? 如何使用正则表达式以开始字符分隔字符串匹配以下任何&lt;= | &gt; = | = | != - How to split a string using regex with beginning character matches any of this <= | >= | = | != 正则表达式或jQuery的某些字符后拆分字符串 - regex or jquery to split string after certain character 如何用JavaScript正则表达式替换href中的所有内容? - How can I replace everything inside an href with JavaScript regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM