简体   繁体   English

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

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

I have 2 strings that use the same letters but one of them contains empty spaces at the end and between words我有2 个使用相同字母的字符串,但其中一个字符串的末尾和单词之间包含空格

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

i want to ignore these empty spaces from 2 strings to only compare strings by the rest of chars in order to get a boolean result equal to true when i do so message === message1我想忽略 2 个字符串中的这些空格,只比较字符的 rest 的字符串,以便在我这样做时获得等于 true 的 boolean 结果message === message1

imo this need a regex imo 这需要一个正则表达式

Yes, you can use str.replace(/\s+/g, '') to remove the spaces then simply compare the strings是的,您可以使用str.replace(/\s+/g, '')删除空格然后简单地比较字符串
That would look something like this:这看起来像这样:

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

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

You can create a function utilizing the String.replaceAll() method like so:您可以使用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))

Alternatively, you can use String.replace() method with regex like you mentioned或者,您可以像您提到的那样将String.replace()方法与正则表达式一起使用

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


console.log(stringsMatchRegex(message, message1))

I would suggest also using String.toLowerCase() on both strings to bypass character case:我还建议在两个字符串上使用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