2015-09-07 53 views
0

我的目標是比較文本文件的第一行輸入從表單中接收的輸入。 我的代碼成功地從文件中讀取,之後我用下面的代碼比較文件中的行與從javascript中的表單輸入

var lines=result.split("\n"); //this line turns file into array 
    var line=lines[i].split(" "); //each index is further changed into an array   
    var sentence=lines[i].split(" ").join(" ").toLowerCase(); //this turns the line/sentence from an array into a String 
    var input=document.getElementById('inputFromForm').value.toLowerCase(); //this line get input from form 

console.log(sentence); //this prints the first line of the text file to the console 
console.log(input);  //this prints the inputFromForm to the text file 
console.log(sentence==input); //check for equality 

我的問題是,這兩個句子都是平等的,但在控制檯說,假以

console.log(sentence==input); 

這怎麼可能,和爲什麼。

+2

try console.log(sentence.trim()== input.trim()); – shreesha

+0

句子和輸入到底是什麼? console.log的作用是什麼? – Liam

+0

你也應該使用'==='而不是'==',[見這裏](http:// stackoverflow。com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) – Liam

回答

1

嘗試以下方法

console.log(sentence.trim()==input.trim()); 

console.log(sentence.toLowerCase()==input.toLowerCase()); 

console.log(sentence.localeCompare(input)==0); 
+0

[使用===](http://stackoverflow.com/questions/ 359494 /做它的事情,哪些等於運營商,與我在使用的JavaScript比較) – Liam

+0

都是字符串什麼是使用=== – shreesha

+0

[*我的建議是永遠不會使用**的邪惡的雙胞胎**。相反,總是使用===和!==。所有剛剛顯示的比較都會產生錯誤===運算符*](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript -comparisons)。 '=='在行爲上非常不一致,通常應該從不**被使用。例如'「abc」== new String(「abc」)// false',都是字符串... – Liam

2

檢查這樣

語法:

str1.localeCompare(str2) 

localeCompare的解釋:它會

  • 返回-1如果str1 str2的前整理
  • 返回0,如果兩個字符串相等
  • 如果str1 str2的排序後返回1

所以

Console.log(sentence.localeCompare(input)); 

所以,你的兩個字符串相等,將提供0

+0

Javascript不是java –

+0

嘿對不起人..你可以使用str1.localeCompare(str2) – vinodh

3

你可以使用不同的方法。

方法一:

var str1 = "ab abcde"; 
    var str2 = "ab abcde"; 
    var n = str1.localeCompare(str2); 
    document.getElementById("demo").innerHTML = n; 
  • 返回-1如果str1 str2的前整理
  • 返回0,如果兩個字符串相等
  • 返回1,如果str1和str2的
  • 後整理

詳情查看:http://www.w3schools.com/jsref/jsref_localecompare.asp

辦法之二:

您可以將每個單詞在句子中使用for循環相匹配。

var s1 = 'Example 1'; 
var s2 = 'Example 2'; 

var s1Array= s1.split(' '); 
var s2Array= s2.split(' '); 

var result = 0; 

for(var i = 0; i<s1Array.length; i++) 
{ 
    if(s1Array[i] !== s2Array[i]){ 
     result=-1; 
     return; 
    } 
} 

if(result<0){//strings not equal} 

這種方法也可以用來找出兩個句子有多相似。我在這裏提到了這個方法,因爲你正在將句子分解成數組,所以你也可以使用這種方法。

相關問題