まず第一に、私はあなたがこれを意味すると思います:
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で動作するバージョンへのリンクです。