Home > Software engineering >  How can I compare two strings ignoring new line characters, white spaces, non-breaking space?
How can I compare two strings ignoring new line characters, white spaces, non-breaking space?

Time:04-01

I need to compare two strings ignoring white spaces, newline characters, non-breaking space. Strings should be equal.

moves the cursor down to \r\n \r\n the next line without returning.

moves the cursor down the next          \r\n \r\n the line without returning.

CodePudding user response:

You can get rid of them with a simple regex.

const pureString = str.replace(/(?:\r\n|\r|\n)/g, '');

And then do your comparison between the two string.

In the regex you are replacing all the \r\n, \r and \n in your string with '', so with nothing.

CodePudding user response:

You could strip the two strings of all the characters you want to ignore.

To strip a string of all the characters you don't want you can use the replace() function. By using \s we remove all spaces, tabs and new-lines, if you want something more specific you have to change the first argument of the replace() function.

string.replace(/\s /g, '')

(see this SO-question to understand how it works: Remove whitespaces inside a string in javascript)

To compare two strings you could use

string1.localeCompare(string2)

(see this SO-question to understand how it works: Optimum way to compare strings in JavaScript? )

If you put these two concepts together, you get

string1 = string1.replace(/\s /g, '')
string2 = string2.replace(/\s /g, '')
string1.localeCompare(string2)

which should answer your question.

  • Related