JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to remove question marks from string in JavaScript?

If a string contains question marks and you want to remove them, call the replace() method and pass /\?/g and an empty string "" as arguments to the replace() method. The replace() method will return a new string in which all the question marks are removed.

Here is the code that removes question marks from the string:

let str = "I?am?learning?JavaScript?";
str = str.replace(/\?/g, '');
console.log(str); //"IamlearningJavaScript"

In a regular expression, the question mark is a quantifier, and matches zero or one time of a character placed before it. Here, we have to match the question mark, so we have escaped it using the backslash.

The g flag is used to select all question marks.

The String.replace() method takes two parameters:

  1. Regular expression or string: It is a pattern or string which you want to replace in a string.
  2. Replacement string: It is the string that will replace the pattern or string specified by the first parameter.

If you simply pass '?' to the replace() method, only the first occurrence of the question mark will be replaced with an empty string. But we want to remove all question marks from the string, so a regular expression is passed with the g flag.

let str = "I?am?learning?JavaScript?";
str = str.replace('?', '');
console.log(str); //"Iam?learning?JavaScript?"

Recommended Posts