1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
In the blogpost, we’ll learn multiple ways to replace (white) spaces in JavaScript. We’ll dive into various string functions, regex, and some array functions, we can use for this task. And then learn some common mistakes we could do, and cement our understanding with a fun practice question. Techniques discussed are not just about replacing spaces; they’re about understanding string manipulation in JavaScript to make your code more efficient and your applications more dynamic. Lets dive in! 👨💻
Lets see various techniques to convert JavaScript Object to Map.
The String.replace()
method in JavaScript is used to search for a pattern in a string and replace it with a specified replacement string. When the pattern is a string, replace()
only targets the first occurrence of that pattern.
This method is ideal to replace only the first occurrence of a space in a string.
"hello world"
is the original string. The replace()
method looks for the first space (" "
) and replaces it with an underscore ("_"
). As a result, "hello world"
becomes "hello_world"
, with only the first space being replaced.const originalString = "hello world. Do not remove space here.";
const replacedString = originalString.replace(" ", "_");
console.log(replacedString);
// Output: "hello_world. Do not remove space here."
To replace all occurrences of a pattern in a string, you can use a regular expression with the global (g
) flag. This flag tells the replace()
method to search for all matches in the string, not just the first one.
Ideal to replace every space in a string, not just the first.
/ /g
is a regular expression where the space character (" "
) is the pattern and g
is the global flag.replace()
method uses this regex to find and replace all spaces with underscores.const originalString =
"hello world. Also Remove Spaces Here";
// Regular expression for a space with a global flag
const regex = / /g;
const replacedString = originalString.replace(regex, "_");
console.log(replacedString);
// Output: "hello_world._Also_Remove_Spaces_Here"
The String.replaceAll()
method was introduced in ES2021 (ECMAScript 2021) as a more intuitive way to replace all occurrences of a pattern in a string, without needing to use a regular expression.
Ideal, to replace all occurrences of a particular substring (like a space) with another substring (like an underscore).
In following example, replaceAll()
method is used to replace all instances of the space character with underscores.
Regex overload of the function can also be used though.
const originalString =
"hello world. Also Remove Spaces Here";
const replacedString = originalString.replaceAll(" ", "_");
// or even regex could have been used in place of space:
// const replacedString = originalString.replaceAll(/ /g, "_");
console.log(replacedString);
// Output: "hello_world._Also____Remove_Spaces_Here"
This technique involves two main methods: split()
and join()
.
The split()
method divides a string into an ordered list of substrings by separating it at each occurrence of a specified separator string (in this case, a space) and returns an array of these substrings.
The join()
method then combines all elements of the array into a single string, inserting a specified separator (an underscore) between each element.
Useful when you need to process individual words or segments of a string before joining them back together.
In following example, originalString
is split into an array using split(" ")
.
Then, join("_")
combines these elements into a single string, inserting an underscore between each word.
const originalString =
"hello world. Also Remove Spaces Here";
// Splitting by space
const wordsArray = originalString.split(" ");
console.log(wordsArray);
//Output: ['hello', 'world.','Also','', '','','Remove','Spaces','Here']
// Joining with underscore
const joinedString = wordsArray.join("_");
console.log(joinedString);
// Output: "hello_world._Also____Remove_Spaces_Here"
The \s
in a regular expression represents any whitespace character (including spaces, tabs, and newlines). When used with the replace()
method and the global flag (g
), it can replace all kinds of whitespace in a string with a specified replacement.
Ideal when the goal is to replace not just regular spaces but all types of whitespace in a string.
**/\s/g**
is a regex that matches every whitespace characters (multiple \n, \t, ' '
) our string. And all of them are easily replaced by ‘_’.// 💩 Nasty combination of \n,\t and ' '.
const originalString =
"\thello world.\n Also\t Remove Spaces Here\n";
const replacedString = originalString.replace(/\s/g, "_");
console.log(replacedString);
// Output: "_hello_world.__Also__Remove_Spaces_________Here_"
With just a + sign extra in our regex, the \s
+ regex replaces consecutive whitespace character (including spaces, tabs, and newlines).
Ideal when the goal is to replace consecutive whitespaces in a string.
**/\s+/g**
is a regex that matches every consecutive whitespace characters (multiple \n, \t, ' '
) our string and replaces with single ‘_’.// 💩 Nasty combination of \n,\t and ' '.
const originalString =
"\thello world.\n Also\t Remove Spaces Here\n";
// Note the in regex.
const replacedString = originalString.replace(/\s+/g, "_");
console.log(replacedString);
// Output: "_hello_world._Also_Remove_Spaces_Here_"
The replace()
method can also take a function as its second argument. This function is called for each match, and the returned value from the function is used as the replacement string. This allows for more dynamic and complex logic in the replacement process.
Ideal when the replacement logic is not straightforward and depends on the context or content of each match.
replace()
checks each whitespace (using /\s/g
as explained in previous section) and replaces it an emoji respective to the type of whitespace character.const originalString = "hello universe !\ncant\tbreathe!";
const replacedString = originalString.replace(
// regex for whitespace chars (\n,\t,' ')
/\s/g,
// Add custom logic for replacement
(match) => {
if (match === " ") {
return "🚀";
} else if (match === "\n") {
return "🆕";
} else if (match === "\t") {
return "💊";
} else {
return match;
}
},
);
console.log(replacedString);
// Output: "hello🚀universe🚀🚀!🆕cant💊breathe!
We can chain multiple string methods to perform complex transformations in a concisely. Like trim()
, replace()
, and toLowerCase()
can be combined to achieve specific formatting goals.
Ideal to perform several operations on a string in a specific order, such as trimming whitespace, changing case, and replacing characters.
trim()
is first used to remove any leading and trailing spaces from the string " Hello World "
.toLowerCase()
method then converts all characters to lowercase, resulting in "hello world"
.replace(/ /g, "_")
replaces all spaces with underscores, producing "hello_world"
.const originalString = " Hello World ";
const formattedString = originalString
.trim()
.toLowerCase()
.replace(/ /g, "_");
console.log(formattedString); // Output: "hello_world"
Array.map()
method creates a new array populated with the results of calling a provided function on every element in the calling array. When combined with string manipulation, this method can be used to process each character or segment of a string individually.
Ideal for situations where you need to apply a specific transformation or set of rules to each individual character or segment of a string.
In following example, "hello world"
is first converted into an array of its characters using split("")
.
The map()
function is then used to iterate over each character, replacing spaces with underscores.
Finally, join("")
recombines the array elements into a single string, resulting in "hello_world"
.
const originalString = "hello world";
const arrayFromString = originalString.split(""); // Convert to array
const processedArray = arrayFromString.map(character => {
return character === " " ? "_" : character;
});
const rejoinedString = processedArray.join("");
console.log(rejoinedString); // Output: "hello_world"
Template literals in JavaScript allow for the creation of strings with embedded expressions. These literals provide an easier way to build strings, especially when incorporating variables and expressions. You can use string methods directly on template literals for further manipulation.
Ideal when dealing with strings that are constructed dynamically and require subsequent space replacement.
name
.replace()
method with the global flag is then used to replace all spaces in the template literal with underscores.const name = "John Doe";
const greeting = `Hello ${name}`;
const formattedGreeting = greeting.replace(/ /g, "_");
console.log(formattedGreeting); // Output: "Hello_John_Doe"
/ /g
) when you want to replace all occurrences in a string. Else only 1 occurence replaced./\s+/g
can replace consecutive whitespaces with a single replacement string, but regex **/\s/g**
replaces every match with replacement string.In the spirit of Test Driven Learning ( 😁), lets test our understanding by solving a problem.
Write a JavaScript function that transforms any string by replacing each set of consecutive spaces with an emoji. The emoji replacement follows a cyclic pattern: for the first set of consecutive spaces, use
1️⃣
; for the second,2️⃣
; for the third,3️⃣
; and for the fourth,🚀
. Then, repeat this cycle for subsequent sets of consecutive spaces.
- The input string consists only of alphabets and spaces.
- Consecutive spaces, regardless of the count, are replaced with a single emoji.
- The function handles empty strings and strings without consecutive spaces.
*Problem (JavaScript)
function galacticSpaceEmojifier(str) {
// > > > 👉 Write code here 👈 < < <
}
console.log(galacticSpaceEmojifier("Ready for launch"));
// Output: "Ready1️⃣for2️⃣launch"
console.log(galacticSpaceEmojifier("T minus 10 seconds to launch"));
// Output: "T1️⃣minus2️⃣103️⃣seconds🚀to1️⃣launch"
console.log(galacticSpaceEmojifier("3 2 1 Launch !"));
// Output: "31️⃣22️⃣13️⃣Launch🚀"
console.log(galacticSpaceEmojifier(""));
// Output: ""
console.log(galacticSpaceEmojifier(" "));
// Output:️ "1️⃣"
console.log(galacticSpaceEmojifier("Exploring the vast universe"));
// Output: "Exploring1️⃣the2️⃣vast3️⃣universe"
Please attempt before seeing the Answer:
function galacticSpaceEmojifier(str) {
let result = '';
let spaceCount = 0;
let emojiIndex = 0;
const emojis = ['1️⃣', '2️⃣', '3️⃣', '🚀'];
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') {
spaceCount++;
continue;
}
if (spaceCount > 0) {
result += emojis[emojiIndex];
emojiIndex = (emojiIndex + 1) % emojis.length;
spaceCount = 0;
}
result += str[i];
}
// Add emoji for trailing spaces
if (spaceCount > 0) {
result += emojis[emojiIndex];
}
return result;
}
Explanation:
galacticSpaceEmojifier
iterates over the characters in the input string str
.spaceCount
). When a non-space character is reached, the function checks if there were any spaces before it.spaceCount > 0
), it adds the next emoji in the cycle to result
.emojiIndex
keeps track of which emoji to use next and cycles through the emojis
array.spaceCount
is reset to 0.Now you are an expert in replacing all (white)spaces in your JavaScript strings.
Keep learning, and keep coding! 🚀👨💻
Feel free to reach out!