How to Replace All Spaces in Javascript?

Follow us on LinkedIn for our latest data and tips!

In computer programming, “find and replace” is a pretty common task. Any programmer that’s interested in working with textual data should have at least a rudimentary idea of how to write a basic find and replace algorithm. In the JavaScript programming language, find and replace functions are not hard to implement. In the following examples, I’ll show a couple of relatively simple techniques that can be utilized to perform robust find and replace tasks. Specifically, I’ll demonstrate how to write a generalized function to replace all spaces with underscores.
Probably the simplest way to go about creating a find and replace function in JavaScript is to leverage the String global object’s String.prototype.replace() method . This method, inherent to all JavaScript strings, can be effortlessly employed by passing in a find argument (the bit of text we hope to find) and a replace argument (the bit of text with which we wish to replace our target(s)). Let’s take a look…
Say we have the string

var str = "This string is kind of spacey.";

We can use the the aforementioned replace() method to target spaces and replace them with underscores. It looks like this:

str = str.replace(" ", "_");

*Note that strings in JavaScript are immutable, and thus simply calling replace() on str won’t change capture the value. We have to assign the returned value of the replace() method back to our str variable… or to a new variable…. in order to use it.

console.log(str); //"This_string is kind of spacey."

Hey, wait a minute… That only caught the first space and replaced it with an underscore. What if we want to find and replace ALL of the spaces? We could use a loop. The JavaScript for loop will work for our purposes here. We could do something like:

var i = 0, strLength = str.length;
for(i; i < strLength; i++) {
 str = str.replace(" ", "_");
console.log(str); //"This_string_is_kind_of_spacey."

It’s not spacey anymore! The loop ran once for each character (including the spaces and any special characters) in str, returning a new string with the first instance of a space replaced, and then assigned that new string value back to our str variable. Over and over for as many characters are contained in str. Pretty slick!
Now, that we know how to go about replacing ALL of a certain character in a string with a new character, let’s generalize it. Let’s create a find and replace function. Here’s how it looks:

function findAndReplace(string, target, replacement) {
 var i = 0, length = string.length;
 for (i; i < length; i++) {
   string = string.replace(target, replacement);
 return string;
console.log(findAndReplace(newStr, " ", "_")); //"I'm_going_to_be_passed_to_the_function,_aren't_I?"
console.log(findAndReplace("No... not me too!", " ", "_")); //"No..._not_me_too!"

Booyah! :) A reusable bit of code that can take string values, a target character/word, and a replacement character/word; and then reassign the value of the string based on the find and replace specifications. Good enough? Sure. But… the way I’ve shown you here isn’t the only way to do it. There are several other ways to go about achieving find and replace functionality within JavaScript, and I encourage you to Google around to see what else is out there!
Lastly here, I do want to show you another way to go about finding and replacing with respect to JavaScript strings. Brace yourselves! the sheer sight of the following term sends shivers down the spines of many… RegEx. I won’t go into too much detail here, and let me be clear… I’m no RegEx expert… however, I do want to show you a pretty simple way to use RegEx to accomplish the same find and replace functionality we recreated above. Here it is:
This bit of code:

var newNewStr = "Not RegEx! Please no!";
newNewStr = newNewStr.replace(/\s/g, "_");
console.log(newNewStr); //"Not_RegEx!_Please_no!"

…employs RegEx syntax and functionality, in conjunction with our now familiar replace() function, to effectively achieve… in just one line… what our multi-line looping function did before. Like I said, I’m no RegEx expert. The toughest part seems to be learning the syntax. I linked the MDN entry above, and there are plenty of tutorials just a Google’s search away. In the simple example above, the / / starts the RegEx expression; the s is RegEx speak for a space. The g means to keep going after finding a match (ie, not stopping after the first match is found). I encourage you, as well as myself!, to continue to learn RegEx syntax and how to use in the context of JavaScript strings. RegEx is an indispensable tool when it comes to pattern matching. Feel free to use the looping technique, as well as other methods you may discover, in the meantime.
Link to code: