I have 2 strings that use the same letters but one of them contains empty spaces at the end and between words
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
imo this need a regex
Yes, you can use str.replace(/\s+/g, '')
to remove the spaces then simply compare the strings
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:
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
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:
const stringsMatch = (str1, str2) => str1.replaceAll(' ', '').toLowerCase() == str2.replaceAll(' ', '').toLowerCase()
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.