Developers, often refer the hyphen (-) as "dash" or "minus". A string value can have letters, numbers, punctuations etc. and many a times we need to eliminate the special characters from string to get only the words.
Now, see this link here. If you see the address bar, the url has a parameter (a string) with "underscores". I wanted to get rid of the underscores to get the words only for the title of my post, using only JavaScript. It’s a just a real time scenario.
I’ll show how using a single line of code in JavaScript, you can replace unwanted characters from a string.
Using RegEx and .replace() Method in JavaScript
<body>
<!--This string has hyphens. I want to remove or replace the hyphens with space.-->
<p>The string: "<span id='cont'>my-time-will-come</span>"</p>
<input type="button" value="Click it" onclick="javascript:removeChar()" />
<p id="newString"></p>
</body>
<script>
function removeChar() {
var value = document.getElementById('cont').innerHTML;
newString.innerHTML = value.replace(/-/g, ' ') + ' (hyphens replaced with spaces)';
}
</script>I have highlighted the .replace() method and the regular expression in the above script.
See the parameter value inside the replace() method. I have two forward slash and a "hyphen" (-) in between. Followed by the letter g, which means it will do a global search of the hyphen (or any given character) in the string.
Now, change the hyphen with an underscore (_).
Replace Hyphens and UnderScores in One Line Code in JavaScript
You can use the same code from the above exmaple to replace "both" hyphens and underscores (if any) in a string, using just a one line code.
<body>
<p>
The string: "<span id='cont'>my-time-will_come</span>"
</p>
<input type="button" value="Click it" onclick="javascript:removeChar()" />
<p id="newString"></p>
</body>
<script>
function removeChar() {
var value = document.getElementById('cont').innerHTML;
newString.innerHTML = value.replace(/-/g, ' ').replace(/_/g, ' ') + ' (hyphens and underscore replaced with spaces)';
}
</script>
</html>If you see careful, the string that the code is updating, has few hyphens and an underscore. You can use multiple .replace() methods in a single line code.
Well, this is one of the simplest methods to get rid of unwanted characters in a string, using plain JavaScript.
Do you know you can use array.flatMap() method to find "Even numbers" in JavaScript. Its a simple method and very few know the trick.
