Js Add Space Before Capital Letter
In this tutorial, we cover two examples to add spaces before every capital letter in a string. This is a useful technique when you want to format a string that has no spaces between words, such as a variable name or a hashtag. In the first example, we use regular expressions (regex) to find and replace the capital letters with spaces. In the second example, we use a JavaScript custom method to loop through the string and insert spaces where needed.
Thanks for your feedback!
Your contributions will help us to improve service.
Example 1 : Javascript Add Space Before Capital Letter
In this Example, we will learn how to add a space before every capital letter in a string using JavaScript, such as "FontAwesomeIcons" to "Font Awesome Icons". To do this, you can use the following regex: /([A-Z])/g.
Javascript regex add space before capital letter
<script>
function insertSpaceBeforeCapitalLetters(str) {
return str.replace(/([A-Z])/g, " $1").trim();
}
</script>
Output of Javascript Insert space before capital letters
Example 2 : Js Add Space Before Capital Letter Javascript Without Regex
In this second example of this tutorial, we will show you how to add a space before every capital letter in a string using JavaScript. This is a common task when you want to convert a camelCase or PascalCase string into a more readable format. We will use a custom method without using regular expressions (regex) to achieve this goal.
<script>
function addSpaceBeforeCapital(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i].toUpperCase() && str[i] !== ' ' && i !== 0) {
result += ' ';
}
result += str[i];
}
return result;
}
</script>