Skip to content

Instantly share code, notes, and snippets.

@thomaslang
Created March 10, 2009 19:37
Show Gist options
  • Save thomaslang/77090 to your computer and use it in GitHub Desktop.
Save thomaslang/77090 to your computer and use it in GitHub Desktop.
getLiteralStrings = function (queryString) {
// this function steps through the input string, recognizes literal strings,
// remembers their position in the input string and returns an array that
// contains objects like this:
// {startPoint: n, endPoint: m, sequenceOfCharacters: s}
var currentlyInString = false;
var delimeterOfCurrentString = "";
var numberOfCurrentString = 0;
var isStringDelimeter = {"'": true, '"': true};
var isEscapeCharacter = {"\\": true};
var currentCharacter = "";
var previousCharacter = "";
var literalStrings = []; //to be returned
// first find the strings start- and end-points:
for (var i=0; i < queryString.length; i++) {
currentCharacter = queryString[i];
if ( currentlyInString ) {
if ( currentCharacter == delimeterOfCurrentString
&& ! isEscapeCharacter[previousCharacter] ) {
currentlyInString = false;
literalStrings[numberOfCurrentString].endPoint = i;
numberOfCurrentString++;
};
}
else {
if ( isStringDelimeter[currentCharacter] ) {
currentlyInString = true;
delimeterOfCurrentString = currentCharacter;
literalStrings[numberOfCurrentString] = {startPoint: i};
};
};
previousCharacter = currentCharacter;
};
// then extract the strings:
return literalStrings;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment