Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

Answer from epascarello on Stack Overflow
Top answer
1 of 6
179

Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

2 of 6
7

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

var newString = "développeur & intégrateur";

newString = replaceAccents(newString);
newString = newString.replace(/[^A-Z0-9]+/ig, "_");
alert(newString);

/**
 * Replaces all accented chars with regular ones
 */
function replaceAccents(str) {
  // Verifies if the String has accents and replace them
  if (str.search(/[\xC0-\xFF]/g) > -1) {
    str = str
      .replace(/[\xC0-\xC5]/g, "A")
      .replace(/[\xC6]/g, "AE")
      .replace(/[\xC7]/g, "C")
      .replace(/[\xC8-\xCB]/g, "E")
      .replace(/[\xCC-\xCF]/g, "I")
      .replace(/[\xD0]/g, "D")
      .replace(/[\xD1]/g, "N")
      .replace(/[\xD2-\xD6\xD8]/g, "O")
      .replace(/[\xD9-\xDC]/g, "U")
      .replace(/[\xDD]/g, "Y")
      .replace(/[\xDE]/g, "P")
      .replace(/[\xE0-\xE5]/g, "a")
      .replace(/[\xE6]/g, "ae")
      .replace(/[\xE7]/g, "c")
      .replace(/[\xE8-\xEB]/g, "e")
      .replace(/[\xEC-\xEF]/g, "i")
      .replace(/[\xF1]/g, "n")
      .replace(/[\xF2-\xF6\xF8]/g, "o")
      .replace(/[\xF9-\xFC]/g, "u")
      .replace(/[\xFE]/g, "p")
      .replace(/[\xFD\xFF]/g, "y");
  }

  return str;
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Source: https://gist.github.com/jonlabelle/5375315

🌐
CoreUI
coreui.io › answers › how-to-remove-special-characters-from-a-string-in-javascript
How to remove special characters from a string in JavaScript · CoreUI
May 20, 2026 - Use replace() with a regular expression to remove special characters from a string. const text = 'Hello@#$% World!!!' const cleaned = text.replace(/[^a-zA-Z0-9\s]/g, '') // Result: 'Hello World' The replace() method with the regular expression ...
Discussions

Removing special characters from a string
Currently working on making a palindrome function. I have the gist of it. Just can’t get this last part. I’ve tried so many examples from so many stockoverflow posts and this still doesn’t work for me. Can someone help me figure out what’s wrong? var str = "abc's test#s"; ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
13
0
July 30, 2017
Remove all special characters except space from a string using JavaScript - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I want to remove all special characters except space from a string using JavaScript. More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to remove spaces and special characters from string? - Stack Overflow
I have a function that returns true if a character is a form of punctuation and I'm trying to write another function that accepts a string and removes the spaces and punctuation marks while calling... More on stackoverflow.com
🌐 stackoverflow.com
lightning web components - How to remove symbol and space from a string in JavaScript - Salesforce Stack Exchange
How to remove the extra space. ... Not sure, why "-" is there. It is what it is. This value is coming from a 3rd party system. We are consuming it. This "Premium+-+Mobile+Plan" is a whole string . More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
June 12, 2023
🌐
RSWP Themes
rswpthemes.com › home › javascript tutorial › how to remove spaces and special characters from a string in javascript
How to Remove Spaces and Special Characters from a String in JavaScript
June 3, 2025 - Regex is often the fastest for complex patterns. For simple tasks like removing spaces, string methods like trim() or split()/join() can be sufficient and more readable. Cleaning strings in JavaScript is straightforward with regex or string methods.
🌐
freeCodeCamp
forum.freecodecamp.org › programming
Removing special characters from a string - Programming - The freeCodeCamp Forum
July 30, 2017 - Currently working on making a palindrome function. I have the gist of it. Just can’t get this last part. I’ve tried so many examples from so many stockoverflow posts and this still doesn’t work for me. Can someone help me figure out what’s wrong? var str = "abc's test#s"; str.replace(/[&\/\\#,+()$~%.'":*? {}]/g,'_'); console.log(str);
🌐
Coding Beauty
codingbeautydev.com › home › posts › how to remove special characters from a string in javascript
How to Remove Special Characters From a String in JavaScript
October 13, 2022 - So the regex matches any character ... digit or space, and the replace() method returns a new string with all of these characters removed from the original string. The g (global) flag specifies that every occurrence of the pattern should be matched. If we don’t pass a global flag, only the first special character ...
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-remove-special-characters-from-string
Remove special Characters from a String in JavaScript | bobbyhadz
We used the plus + symbol to match one or more occurrences of a space and replaced multiple spaces with a single space. An alternative approach to using the caret ^ symbol to specify the characters we want to keep is to specify the special ...
Find elsewhere
Top answer
1 of 1
1

Some issues:

  • The inner condition should in fact be the opposite: you want to do nothing when it is a punctuation character, i.e. you don't want to add it to the result. Only in the other case you want to do that.

  • The call !compress(i) is wrong: first of all that function expects a string, not an index, and it returns a string, not a boolean (so to perform ! on it). It seems like you want to call your function recursively, and although that is an option, you are also iterating over the string. You should do one of the two: recursion or iteration.

  • You reference a variable ch in the compress function which you have not defined there.

So, if you want to write compress the iteration way, change your code as follows:

var compress = function(s) {
    var result = "", ch; // define ch.

    //loop to traverse s
    for (var i = 0; i < s.length; i++) {
        ch = s[i]; // initialise ch.
        if (!isPunct(ch)) result = result + ch; // only add when not punctuation
    }
    return result;
}

If on the other hand you want to keep your recursive call to compress, then you should do away with your for loop:

var compress = function(s) {
    var result = "", ch, rest;

    if (s.length == 0) return '';
    result = compress(s.substr(1)); // recursive call
    ch = s[0];
    if (!isPunct(ch)) result = ch + result;
    return result;
}

The function isPunct also has a strange thing happening: it assigns a boolean value to ch in the if expression. This does not make your function malfunction, but that assignment serves no purpose: the match method already returns the boolean you need for your if condition.

It is also not really nice-looking to first evaluate a boolean expression in an if to then return that same value in the form of false and true. This you can do by just returning the evaluated expression itself:

var isPunct = function(ch) {
    return ch.match(/[,.!?;:'-]/g);
}

On a final note, you don't really need the isPunct function if you only use it in compress. The whole logic can be performed in one function only, like this:

let compress = s => s.replace(/[,.!?;:'-]/g,'');
// Demo:  
console.log(compress('a,b,c')); // abc

If you prefer to keep isPunct and don't want to repeat the regular expression elsewhere, then you can do the replace like this:

let isPunct = ch => ch.match(/[,.!?;:'-]/g);

let compress = s => Array.from(s).filter(ch => !isPunct(ch)).join('');
// Demo:  
console.log(compress('a,b,c')); // abc

Note how the use of ES6 arrow functions and ES5 Array methods makes the code quite lean.

🌐
YouTube
youtube.com › watch
Remove Space & Special Characters While Typing Using JavaScript & jQuery ! - YouTube
Sometimes you need to remove space and special characters from user inputs, while user types in text box,in this video, you will learn how to remove space an...
Published   April 8, 2022
🌐
CodePen
codepen.io › MoyArt › pen › gjKLEj
JS - REGEX to remove spaces and special characters
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-remove-spaces-from-a-string-using-javascript
How to Remove Spaces From a String using JavaScript? | GeeksforGeeks
The _.trim() method method removes leading and trailing whitespace from a string. ... JavaScript string.replace() method is used to replace a substring. With Regular expressions pattern we can find all spaces (/\s/g) and globally replace all ...
Published   November 14, 2024
🌐
Futurestud.io
futurestud.io › tutorials › remove-extra-spaces-from-a-string-in-javascript-or-node-js
Remove Extra Spaces From a String in JavaScript or Node.js
Use JavaScript’s string.replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s. Expand the whitespace selection from a single space to multiple using the \s+ RegEx. Combine the string.replace() method and the RegEx and ...
🌐
SmartWiki
wiki.smartsimple.com › wiki › Removing_Special_Characters
Removing Special Characters - SmartWiki
including the space key) and immediately replace them with an underscore (_): onkeyup="this.value=this.value.replace(/[\W]/g,'_');" 2. The following code will look for # [ $ ] and \ and replace them with an underscore (_) once the user has clicked away from the field: onchange="this.value=this.value.replace(/[#[$\]\\@]/g,'_');" Note: if you also want to replace double quotes you must omit the double quotes around the javascript statement:
🌐
freeCodeCamp
freecodecamp.org › news › javascript-remove-char-from-string
JS Remove Char from String – How to Trim a Character from a String in JavaScript
May 9, 2024 - This method removes only any whitespaces from the end of the string. The whitespaces at the beginning of the string will remain. To remove a specific character from a string in JavaScript, you can use the replace() method.
🌐
Intellipaat
intellipaat.com › home › blog › remove all special characters except space from a string using javascript
Remove all special characters except space from a string using JavaScript - Intellipaat
February 3, 2026 - So far in this article, we have learned how we can remove all special characters except space from a string using regular expressions in JavaScript. We have to use replace() function and match() to do this task.