Home > Enterprise >  How to check for value ignoring whitespaces?
How to check for value ignoring whitespaces?

Time:03-05

Client sends this object:

const CLIENT = {
  username: "@johndoe12",
  nickname: "John Doe",
  password: "1234"
}

Node.js:

...
const {
    rows: [{ exists }],
} = await pgPool.query(
    "SELECT exists (SELECT true FROM users WHERE username=($1) AND nickname=($2) );",
    [CLIENT.username, CLIENT.nickname]
);
if (exists) {

    res.json({
        status: "failed",
        message: "User with that username or nickname already exist.",
    });
} else if (!exists) {
//create user
...
}

//.replaceAll() removes all whitespaces

Problem: Whitespaces count as valid string, I thought about .replaceAll(/\s/g, ""), but the string would be saved as "JohnDoe" with no space and reusing it would be a problem.

{username: "@johndoe12 ", {"nickname": "John Doe   "}}  is not same as {username: "@johndoe12", nickname: "John Doe"}?

result:

5   "@Bob"  "Bob Carla "    "123"
6   "@Bob"  "Bob Carla  "   "123"
7   "@Bob"  "Bob Carla   "  "123"

CodePudding user response:

I am not sure what you are asking, but if you want to ignore leading and training blanks, you can use the PostgreSQL function trim:

... WHERE trim(nickname) = trim('John Doe  ')

If you want to remove all blanks, try

... WHERE translate(nickname, ' ', '') = translate('John  Doe ', ' ', '')

CodePudding user response:

If you want to trim blacks only on sides exclude spaces between words, you can trim input on your own (on backend side) like this:

const trimLeft  = str => str[0] === ' ' 
  ? trimLeft(str.slice(1)) 
  : str;
const trimRight = str => str[str.length - 1] === ' '
  ? trimRight(str.slice(0, -1))
  : str;
  
const trim = str => trimLeft(trimRight(str));


const results = [
  trim('Bob Carla'),
  trim('Bob Carla  '),
  trim('   Bob Carla  '),
  trim(' Bob    Carla  '),
];

for (const result of results) {
  console.log(result, result.length);
}

  • Related