簡體   English   中英

使用 JavaScript 刪除字符串中的空格

[英]Remove whitespace in a string with JavaScript

我試圖讓這個回文生成器工作,但我無法弄清楚如何讓 js 從多字回文中的單詞之間刪除空格。 賽車不斷返回虛假。 賽車回歸真實,因此部分代碼正在運行。 如何讓 JS 忽略“種族”和“汽車”之間的空白,以便賽車回歸真實?

function palindrome(word) {
    var len = word.length;
    word = word.replace(/ +/g, "");


    for (var i = 0; i < Math.floor(len/2); i++ ) {
      if (word[i] !== word[len - 1 - i]) {
      return "FALSE";
       }
     }
     return "TRUE";
}

console.log(palindrome("race car"))

只需您可以做到這一點,

 let str = ' aaa aa '; str = str.replace(/\s+/g,''); console.log(str);

希望這段代碼對你有幫助

var str = " this is a sample "
var res = str.replace(/ /g, "");
console.log(res);

O/P - 'thisisasample'

你可以試試這個:

word = word.replace(/\s+/g, " ").trim();

它也會從前面和后面刪除空格。

您可以在將其傳遞給回文函數之前使用正則表達式執行此操作:

'race car'.replace(/\s+/, "") 

'race car' 也可以替換為包含您的字符串的任何變量。

希望這可以幫助:

 function palindrome(str) { str = str.replace(/\s+/g, ''); // Delete whitespaces. return str.split('') // Convert the string into an array. .reverse() .join('') === str; // Convert the array into the string. } console.log(palindrome("race car"));

你可以試試這個。

replace(/\s+/, " ")
 var len = word.length; 

在換詞之后得到 len 而不是之前;

 function palindrome(word) { word = word.replace(/ +/g, ""); var len = word.length; for (var i = 0; i < Math.floor(len / 2); i++) { if (word[i] !== word[len - 1 - i]) { return "FALSE"; } } return "TRUE"; } console.log(palindrome("race car"))

  word = word.replace(/ +/g, "");

建議使用正則表達式:

  word = word.replace(/\s+/g, "");     

在刪除空格之前,您正在使用len 因此,您要求返回的最后一個元素undefined ,這將導致不匹配和 FALSE 輸出。

嘗試以下代碼段:

 function palindrome(word) { word = word.replace(/ +/g, ""); var len = word.length; for (var i = 0; i < Math.floor(len/2); i++ ) { if (word[i] !== word[len - 1 - i]) { return "FALSE"; } } return "TRUE"; } console.log(palindrome("race car"))

請使用以下代碼刪除兩個單詞之間的空格。

word = word.replace(/\s/g, ''));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM