// Strings keep an index of each character, starting at 0. // The substr(num1, num2) method takes two integer arguments: // num1 is the index of the starting character of the requested substring; // num2 is number of characters that are sought; // string_name.substr(0, 2) returns the first two characters of the string // if num2 is omitted, the rest of the string starting at num1 is shown; // likewise if num2 extends beyond the string length // if num1 is negative, counting starts from the end of the string function showSubString(startAt, endAt, field, fieldToSet) { if (endAt < 0) { // avoid an error in case number of characters is negative endAt = endAt * -1; } if ((startAt < 0) && (startAt * -1) > field.value.length) { alert("String is too short for request.\nShowing complete string."); fieldToSet.value = field.value; } else if ((startAt < 0) && (startAt * -1) <= field.value.length && endAt > 0) { alert("Showing string starting from character index " + (field.value.length + parseInt(startAt)) + "\nto character index " + (field.value.length + parseInt(startAt) + parseInt(endAt)) + "." ); fieldToSet.value = field.value.substr(startAt, endAt); } else if ((startAt < 0) && ((startAt * -1) <= field.value.length) && (endAt == "" || endAt == 0)) { alert("Showing remaining string starting at character index " + (field.value.length + parseInt(startAt)) + "."); fieldToSet.value = field.value.substr(startAt); } else if (endAt == "" || endAt == "0") { alert("Showing complete string starting an character index " + startAt + "." ); fieldToSet.value = field.value; } else { fieldToSet.value = field.value.substr(startAt, endAt); } }