[英]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.我试图让这个回文生成器工作,但我无法弄清楚如何让 js 从多字回文中的单词之间删除空格。 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?
如何让 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"))
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. 'race car' 也可以替换为包含您的字符串的任何变量。
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;在换词之后得到 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"))
and和
word = word.replace(/ +/g, "");
suggest use regular expression:建议使用正则表达式:
word = word.replace(/\s+/g, "");
You are taking len
before removing white spaces.在删除空格之前,您正在使用
len
。 So the last element you were asking returning undefined
, that's result in no match and FALSE output.因此,您要求返回的最后一个元素
undefined
,这将导致不匹配和 FALSE 输出。
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, ''));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.