简体   繁体   中英

Remove whitespace in a string with JavaScript

I'm trying to get this palindrome generator to work, and I cannot figure out how to get js to remove the white space from between the words in multi-word palindromes. race car keeps coming back false. racecar comes back true, so part of the code is working. How do I get JS to ignore the white space between "race" and "car" so that race car comes back as true?

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"))

Simply You can do this,

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

Hope this code will help you

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

O/P - 'thisisasample'

You can try this:

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

It will remove the spaces from the front and the back as well.

You can do this with a regex before passing it to the palindrome function:

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

'race car' can also be replaced by any variable containing your string.

Hope, this helps:

 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; 

get the len after word change not before;

 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"))

and

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

suggest use regular expression:

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

You are taking len before removing white spaces. So the last element you were asking returning undefined , that's result in no match and FALSE output.

Try following snippet:

 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, ''));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM