2017-05-23 241 views
1

函數compress()將接受一個句子並返回一個字符串,其中刪除了所有的空格和標點符號。
此功能必須調用isWhiteSpace()isPunct()從字符串中刪除標點符號和空格

我已經完成了調用的函數,但是我不知道我的js代碼中缺少什麼來調用函數。

function compress(sent) { 
    var punc = "; : . , ? ! - '' ""() {}"; 
    var space = " "; 
    if (punc.test(param)) { 
     return true 
    } else { 
     return false 
    } 
    if (space.test(param)) { 
     return true 
    } else { 
     return false 
    } 
    isWhiteSpace(x); 
    isPunct(x); 
} 
+1

'punc'應該是一個正則表達式,或者你的測試應該是'.includes',而不是'.test'。此外,你的代碼永遠不會傳遞第一個「if/else」對,因爲它們覆蓋了100%的可能性。 – nem035

+0

您不能將語音標記直接放入變量中。您需要使用\轉義它們。所以var punc =「;:。,?! - \'\」(){}「;' –

+0

你的函數compress實際上並沒有壓縮任何東西......它所做的只是返回包含標點符號的天氣 –

回答

1

您可以利用String.indexOf設計isPunct功能。

function isPunct(x) { 
    // list of punctuation from the original question above 
    var punc = ";:.,?!-'\"(){}"; 

    // if `x` is not found in `punc` this `x` is not punctuation 
    if(punc.indexOf(x) === -1) { 
     return false; 
    } else { 
     return true; 
    } 
} 

解決isWhiteSpace比較容易。

function isWhiteSpace(x) { 
    if(x === ' ') { 
     return true; 
    } else { 
     return false; 
    } 
} 

你可以把它放在一起用循環,檢查在使用String.charAt字符串中的每個字符:

function compress(sent) { 

    // a temp string 
    var compressed = ''; 

    // check every character in the `sent` string 
    for(var i = 0; i < sent.length; i++) { 
     var letter = sent.charAt(i); 

     // add non punctuation and whitespace characters to `compressed` string 
     if(isPunct(letter) === false && isWhiteSpace(letter) === false) { 
      compressed += letter; 
     } 
    } 

    // return the temp string which has no punctuation or whitespace 
    return compressed; 
} 
0

如果你在一個函數返回的東西,將停止執行。

從我所看到的,你的函數不需要任何回報......所以,你應該只是這樣做

function compress(sent) { 
    var punc = ";:.,?!-'\"(){} "; 
    var array = punc.split(""); 
    for (x = 0; x < array.length; x++) { 
     sent = sent.replace(array[x], ""); 
    } 
    isWhiteSpace(x); 
    isPunct(x); 
    return sent; 
} 
4

此功能必須調用isWhiteSpace()和ispunct判斷()。

因此,您已經有兩個函數,我假設傳回的字符是空格或標點符號時,返回true。然後,您不需要,也不應該通過在您的代碼中爲空白和標點符號實現基於正則表達式的重複文本來複制此功能。保持乾爽 - 不要重複自己。

基於這兩個功能看上去就像一個compress功能如下:

function isWhiteSpace(char) { 
 
    return " \t\n".includes(char); 
 
} 
 

 
function isPunct(char) { 
 
    return ";:.,?!-'\"(){}".includes(char); 
 
} 
 

 
function compress(string) { 
 
    return string 
 
     .split("") 
 
     .filter(char => !isWhiteSpace(char) && !isPunct(char)) 
 
     .join(""); 
 
} 
 

 
console.log(compress("Hi! How are you?"));

我同意,一個正則表達式測試將可能是到去選擇在真實的場景:

function compress(string) { 
    return string.match(/\w/g).join(""); 
} 

但是,您特別要求提供isWhiteSpaceisPunct的解決方案。

相關問題