Home > Software design >  How to check that there are no other characters in the string except letters and whitespace
How to check that there are no other characters in the string except letters and whitespace

Time:07-31

function getAbbreviation(str) {
}
console.log(getAbbreviation('some1 company name'))

How to check that there are no other characters in the string except letters and whitespace

CodePudding user response:

You can use regular expression, You can use ^ to try to find any character that isn't [a-z] with i the case insensitive flag which means any English letter if capital or small, and \s means white space.

So, the regular expression will test the string, if there are any character that isn't an English letter or a white space.

function getAbbreviation(str) {
  return !/[^a-z\s]/i.test(str)
}
console.log(getAbbreviation('some company name'))

CodePudding user response:

You can use string replace to remove the special characters using regex (except letters and whitespace)

function getAbbreviation(str) {
  return str.replace(/[^a-zA-Z ]/g, "");
}
  • Related