DOM修改:
1、全文单词首字母大写---2013 腾讯
var toCapitalize = function (str){ var aStr1 = str.split(" "); var aStr2 = []; for (var i=0; i<aStr1.length; i++){ var capitalizeEle = aStr1[i].charAt(0).toUpperCase() + aStr1[i].slice(1); aStr2.push(capitalizeEle); } return aStr2.join(" "); } var str1 = "Your organization has made significant technology investments pport solutions can help you opportunities."; alert(toCapitalize(str1))
其实,如果数据不用于后台运算,只是表现上的首字符大写的话,这样就可以了:
#foo{text-transform:capitalize}
算法题:
1、两个字符串A、B ,假设字符串A 长度为m,假设字符串B,长度为n,找出在A中包含的B的所有字符。----2013 腾讯
var aCommonChar = function (a,b){ var result = [],hashTable = {};
//1 历遍第一个参数字符串,删除掉重复的字符,放入结果hash表中。 for (var i = 0; i < a.length; i++){ var name1 = a.charAt(i); if (!hashTable[name1]){ hashTable[name1] = 0; } }
//2 历遍第二个参数字符串,如果第二个字符串中有和上面hash中的键名相同的字符,则修改键值为1。 for (var j=0; j<b.length; j++){ var name2 = b.charAt(j); if (hashTable[name2] === 0){ hashTable[name2] = 1; } } //3 历遍hashTable,把键值为1的键名push进结果数组 for (key in hashTable){ if (hashTable.hasOwnProperty(key) && hashTable[key] === 1){ result.push(key); } } return result; } //test var A = " The Hebrew word for “wonder” means, “a cause of astonishment.” God’s dealings with the Psalmist David had been such that people noticed "; var B = "The disciples were seen as a wonder unto many for basically they were unlearned and ignorant men - Act 4:13. Yet the Apostles felt they were being made a spectacle to the world, 1Co 4:9. "; alert(aCommonChar(A,B))
2 写一个RGB色彩值转化为16进制色彩值的函数,例如RGB(0,255,0)→#00ff00
var sRGBToHex = function (str){ if (str.search(/rgb/i) === -1){//兼容ie6-8,它们的颜色值本身就是16进制的 return str; } var result = "#"; str = str.replace(/rgba?\((.*)\)/gi,"$1"); aStr = str.split(","); for (var i=0; i<3; i++){//这里直接写了3,是因为标准浏览器的色彩值可能包含透明度信息,例如RGBA(0,255,30,0.5) var iColorAlpha = +aStr[i]; if (iColorAlpha < 16){ result += "0" + iColorAlpha.toString(16); }else{ result += iColorAlpha.toString(16); } } return result; }