3 // (c) 2006 Douglas Crockford
5 // Produce an array of simple token objects from a string.
6 // A simple token object contains these members:
7 // type: 'name', 'string', 'number', 'operator'
8 // value: string or number value of the token
9 // from: index of first character of the token
10 // to: index of the last character + 1
12 // Comments of the ; type are ignored.
14 // Operators are by default single characters. Multicharacter
15 // operators can be made by supplying a string of prefix and
17 // characters. For example,
19 // will match any of these:
20 // <= >> >>> <> >= +: -: &: &&: &&
22 /*jslint onevar: false
25 String.prototype.tokens = function (prefix, suffix) {
26 var c; // The current character.
27 var from; // The index of the start of the token.
28 var i = 0; // The index of the current character.
29 var length = this.length;
30 var n; // The number value.
31 var q; // The quote character.
32 var str; // The string value.
34 var result = []; // An array to hold the results.
36 var make = function (type, value) {
38 // Make a token object.
48 // Begin tokenization. If the source string is empty, return nothing.
54 // If prefix and suffix strings are not provided, supply defaults.
56 if (typeof prefix !== 'string') {
59 if (typeof suffix !== 'string') {
64 // Loop through this text, one character at a time.
78 } else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
83 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
84 (c >= '0' && c <= '9') || c === '_') {
91 result.push(make('name', str));
95 // A number cannot start with a decimal point. It must start with a digit,
98 } else if (c >= '0' && c <= '9') {
102 // Look for more digits.
106 if (c < '0' || c > '9') {
113 // Make sure the next character is not a letter.
115 if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '_') {
118 make('number', str).error("Bad number");
121 // Convert the string value to a number. If it is finite, then it is a good
126 result.push(make('number', n));
128 make('number', str).error("Bad number");
133 } else if (c === ';') {
136 if (c === '\n' || c === '\r' || c === '') {
142 // multi-char operator.
144 } else if (prefix.indexOf(c) >= 0) {
149 if (suffix.indexOf(c) < 0) {
155 result.push(make('operator', str));
157 // single-character operator.
161 result.push(make('operator', c));