繁体   English   中英

比较两个字符串的字符并忽略单词之间的空格

[英]compare chars of two strings and ignore white space between words

我有2 个使用相同字母的字符串,但其中一个字符串的末尾和单词之间包含空格

const message = 'Hello javascript world ';
const message1 = 'Hello     javascript world              ' ;

我想忽略 2 个字符串中的这些空格,只比较字符的 rest 的字符串,以便在我这样做时获得等于 true 的 boolean 结果message === message1

imo 这需要一个正则表达式

是的,您可以使用str.replace(/\s+/g, '')删除空格然后简单地比较字符串
这看起来像这样:

const message = 'Hello javascript world ';
const message1 = 'Hello     javascript world              ' ;

const equal = message.replace(/\s+/g, '') == message1.replace(/\s+/g, '');
// true

您可以使用String.replaceAll()方法创建一个 function,如下所示:

const message = 'Hello javascript world ';
const message1 = 'Hello     javascript world              ' ;


const stringsMatch = (str1, str2) =>  str1.replaceAll(' ', '') == str2.replaceAll(' ', '')

console.log(stringsMatch(message, message1))

或者,您可以像您提到的那样将String.replace()方法与正则表达式一起使用

const stringsMatchRegex = (str1, str2) =>  str1.replace(/ /g, '') == str2.replace(/ /g, '')


console.log(stringsMatchRegex(message, message1))

我还建议在两个字符串上使用String.toLowerCase()来绕过字符大小写:

const stringsMatch = (str1, str2) =>  str1.replaceAll(' ', '').toLowerCase() == str2.replaceAll(' ', '').toLowerCase()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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