Skip to main content

Ivan Teoh

Something personal yet public

167-exercise45.js

(Source)

function catNames(paragraph) {
    var result = [];
    var colon = paragraph.indexOf(":");
    allCat = paragraph.slice(colon + 1);
    names = allCat.split(",");
    for (var i = 0; i < names.length; i++) {
        var catName = names[i].split("");
        var startName;
        var endName;
        // Trims whitespace from the left side of the string.
        for (var j = 0; j < catName.length; j++) {
            startName = j;
            if (catName[j] != " ")
                break;
        }
        // Trims whitespace from the right side of the string.
        for (var k = catName.length - 1; k > -1; k--) {
            endName = k;
            if (catName[k] != " ")
                break;
        }
        result.push(names[i].slice(startName, endName+1));
    }
    return result;
}
var paragraph = "born 05/04/2006 (mother Lady Penelope): Red Lion, Doctor" +
  "Hobbles the 3rd, Little Iroquois";
document.write(catNames(paragraph));