gpt4 book ai didi

Javascript 在空格或引号上将字符串拆分为数组

转载 作者:IT王子 更新时间:2023-10-29 03:23:12 30 4
gpt4 key购买 nike

var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix

我希望数组是这样的:

var astr = ["single", "words", "fixed string of words"];

最佳答案

接受的答案并不完全正确。它分隔非空格字符,如 .和 - 并在结果中留下引号。执行此操作以排除引号的更好方法是使用捕获组,例如:

//The parenthesis in the regex creates a captured group within the quotes
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = 'single words "fixed string of words"';
var myArray = [];

do {
//Each call to exec returns the next regex match as an array
var match = myRegexp.exec(myString);
if (match != null)
{
//Index 1 in the array is the captured group if it exists
//Index 0 is the matched text, which we use if no captured group exists
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);

myArray 现在将包含 OP 要求的内容:

single,words,fixed string of words

关于Javascript 在空格或引号上将字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817646/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com