1

基本上,就像你说

var string = 'he said "Hello World"';
var splitted = string.split(" ");

拆分后的数组将是:

'he' 'said' '"Hello World"'

基本上将引号部分视为单独的项目

那么我将如何在javascript中做到这一点?如果扫描仪在一组引号内,我是否必须有一个遍历字符串的 for 循环?或者有没有更简单的方法?

4

2 回答 2

7

您可以使用正则表达式:

var splitted = string.match(/(".*?")|(\S+)/g);

基本上,它首先搜索引号之间的任何字符(包括空格)的字符串,然后搜索字符串中的所有剩余单词。

例如

var string = '"This is" not a string "without" "quotes in it"'; string.match(/(".*?")|(\S+)/g);

将此返回到控制台:

[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
于 2012-12-01T18:52:16.440 回答
0

首先,我认为您的意思是:

var string = 'he said "Hello World"';

现在我们已经解决了这个问题,您对 for 循环的想法部分正确。这是我的做法:

// initialize the variables we'll use here
var string = 'he said "Hello World"', splitted = [], quotedString = "", insideQuotes = false;

string = string.split("");

// loop through string in reverse and remove everything inside of quotes
for(var i = string.length; i >= 0; i--) {
    // if this character is a quote, then we're inside a quoted section
    if(string[i] == '"') {
        insideQuotes = true;
    }

    // if we're inside quotes, add this character to the current quoted string and
    // remove it from the total string
    if(insideQuotes) {
        if(string[i] == '"' && quotedString.length > 0) {
            insideQuotes = false;
        }

        quotedString += string[i];
        string.splice(i, 1);
    }

    // if we've just exited a quoted section, add the quoted string to the array of
    // quoted strings and set it to empty again to search for more quoted sections
    if(!insideQuotes && quotedString.length > 0) {
        splitted.push(quotedString.split("").reverse().join(""));
        quotedString = "";
    }
}

// rejoin the string and split the remaining string (everything not in quotes) on spaces
string = string.join("");
var remainingSplit = string.split(" ");

// get rid of excess spaces
for(var i = 0; i<remainingSplit.length; i++) {
    if(remainingSplit[i].length == " ") {
        remainingSplit.splice(i, 1);
    }
}

// finally, log our splitted string with everything inside quotes _not_ split
splitted = remainingSplit.concat(splitted);
console.log(splitted);​

我确信有更有效的方法,但这会产生与您指定的完全一样的输出。是 jsFiddle 中此工作版本的链接。

于 2012-12-01T18:55:52.543 回答