Home > Blockchain >  How to remove all special characters from the character string that comes as a parameter?
How to remove all special characters from the character string that comes as a parameter?

Time:08-05

I'm practicing Javascript logic exercises to improve in this language and prepare for future interviews and I find myself stuck on something that may seem basic, but I can't find the way around it, I don't know if someone could explain to me how to solve this problem.

The statement says that: The purpose of the FormatString function is to remove all special characters from the character string that comes as a parameter. Only the 26 letters of the English alphabet, numbers 0-9, spaces, and hyphens are allowed.

The program is as follows:

function FormatString(sentence) {
let result = []; 

sentence = sentence.toUpperCase(); 

let i = 0; 
let j = 0;

while (i < sentence.lenght){
    if(
        (sentence.charCodeAt(i) >= 65 && sentence.charCodeAt(i) <=90) || (sentence.charCodeAt(i) >= 48 && sentence.charCodeAt(j) <= 57) || sentence.charCodeAt(i) == 32 ||
        sentence.charCodeAt(i) == 45
    ) {
        sentence[j] = result[i];
        j =1;
    }
    i =1;
}
return result.join(""); 
}

There are supposed to be errors in the exercise, but I can't identify them, I would like to make the code work, sorry if it's something very basic, but I'm still learning. Thank you.

CodePudding user response:

This is the easiest (and most elegant) method to accomplish what you need. Match the items and joined the matched array into a string:

function FormatString(sentence) {
    return sentence.match(/[a-z]|[0-9]|-|\s/gi).join('')
}

To Test:

console.log(FormatString('%this is 1212-33 QB)_'))

CodePudding user response:

First, I don't know if it is part of your exercise or not but you typed sentence.lenght, it is length

second: your code is actually uppercasing the sentence so it would return uppered sentence

you could add

(sentence.charCodeAt(i) >= 97 && sentence.charCodeAt(i) <= 122)

to check for "a-z" letters, don't forget to remove sentence.toUpperCase()

CodePudding user response:

Use replace() method from String and regular expression.

Basically, you want to remove everything that is not a-zA-Z0-9 -, so:

const formatString = (sentence) => sentence.replace(/[^a-zA-Z0-9 -]*/g, '');

More info on the official documentation of RegExp

For replace method: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/replace

CodePudding user response:

You have misspelled length and its causing the output you're getting. And if you want to continue the approach in the example, you have to implement all the other character codes also.

A shorter way would be:

const formatString = (sentence) => sentence.replace(/[^a-z\d\s\-] /igm, '');
  • Related