javascript - 如何在 Javascript 中标记字符串?

标签 javascript arrays string

我有一个字符串:

'"Apples" AND "Bananas" OR "Gala Melon"'

我想把它转换成一个数组

arr = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']

我不知道我是否可以用正则表达式来做。我开始认为我可能必须一次解析每个字符以匹配双引号。

最佳答案

input = '"Apples" AND "Bananas" OR "Gala Melon"'

output = input.match(/\w+|"[^"]+"/g)
// output = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']

正则表达式的解释:

/ - 正则表达式的开始
\w+ - 单词字符序列
| - 或
"[^"]+" - 任何引用(假设没有转义引号)
/g - 正则表达式结束,全局标志(执行多个匹配)

关于javascript - 如何在 Javascript 中标记字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14853404/

相关文章:

java - String.replaceAll 的正则表达式

javascript - 与jquery等高?

javascript - 数组作为 JavaScript 中的变量赋值

python-3.x - 在 Python 中从字符串打印特定切片

javascript - Backbone.js 比较函数,如何实现降序?

php - 分配给任意深的数组索引?

php - 如何在PHP中获取包含组合字符的Unicode字符串的 "rendered length"?

javascript - 是什么导致控制台错误 "Cannot read property ' setAttribute' of undefined at HTMLTableRowElement”

javascript - IE 11、XMLHttpRequest、xhr.upload 未在 Webworker 中设置

php - 获取 php 数组的查询结果并检查其中是否有变量