日期:2014-05-16 浏览次数:20419 次
function duplicateWord(a, b) { if (!a || !b) return; var dict = {}; var result = []; a.replace(/\w+/g, function() { // 获得第一组单词 dict[arguments[0]] = true;; }); b.replace(/\w+/g, function() { // 判断单词是否重复,如果重复添加到结果中 if (dict[arguments[0]]) result.push(arguments[0]); }); return result; } var words = duplicateWord("This is a dog.", "this is a cat."); alert(words);
------解决方案--------------------
给String添加一个函数
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <script> String.prototype.sameElements = function(str){ var arr = new Array(); str = str.replace(".",""); var temp = str.split(" "); for(var i=0;i<temp.length;i++){ if(this.indexOf(temp[i])!=-1){ arr.push(temp[i]); } } return arr; } var str1 = "This is a dog." var str2 = "this is a cat." alert(str1.sameElements(str2)); </script> </HEAD> <BODY> </BODY> </HTML>