简体   繁体   English

如何在非字母字符上分割字符串。 正则表达式JavaScript

[英]How to split a string on non-alphabetic characters. Regex JavaScript

I have a sentence that I want to split into an array of words, but if there is punctuation included I end up with quotes in my array somehow. 我有一个句子,希望将其拆分为单词数组,但是如果包含标点符号,我最终会以某种方式在数组中加上引号。

 console.log("This is an example sentence! Dangit".split(/[\\W/]/)); // Outputs: ["This", "is", "an", "example", "sentence", "", "Dangit"] 

How do I fix this? 我该如何解决?

您可以改用match并寻找文字字符。

 console.log("This is an example sentence! Dangit".match(/\\w+/g)) 

Try [\\W]+ instead, which will combine multiple non-word chars together - 尝试使用[\\W]+ ,它将多个非单词字符组合在一起-

"This is an example sentence! Dangit".split(/[\W/]+/)

Array(6) [ "This", "is", "an", "example", "sentence", "Dangit" ]

单个和多个目标空间和标点符号:

[\s.?!,]+

 console.log("This is an example sentence! Dangit".split(/[\\s.?!,]+/)); 

暂无
暂无

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

相关问题 按非字母字符拆分字符串 - Split string by non-alphabetic characters JS用“ new RegExp()”从字符串中删除非字母字符 - JS Removing non-alphabetic characters with “new RegExp()” from string 至少 2 个非字母字符的 JavaScript 正则表达式 - JavaScript regex for at least 2 non alphabetic characters in any order Javascript 使用正则表达式在不同的特定字符处拆分字符串 - Javascript with Regex to split string at different specific characters 使用javascript从字符串中分离字母字符 - Separate alphabetic characters from a string with javascript 如何修复“未知错误状态:错误:uid必须是一个非空字符串,最多128个字符。”在Firebase函数中 - How To Fix “Unknown error status: Error: The uid must be a non-empty string with at most 128 characters.” in Firebase Functions 在Regex中如何在不在其他字母字符内时查找和替换字符? - In Regex How to find and replace characters when they are not within other alphabetic characters? Javascript正则表达式-在两个字符之间按字符串分割字符串 - Javascript regex - split string by string between two characters 如何在保留空格的同时在空格和非字母数字字符上拆分 javascript 字符串 - How to split a javascript string on spaces and non alphanumeric characters while keeping spaces Javascript Regex将字符串拆分为分组的/连续的字符数组 - Javascript Regex to split a string into array of grouped/contiguous characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM