How to Replace Any Character Inside a String With JavaScript

Learn how to replace any character inside a (string) with JavaScript by using regular expressions (RegEx) and the replace() method.

Let’s say you have a block of text and you meant to use an em dash (—), but by mistake, you used a hyphen (-):

const textBlock =
  "When you’re typing fast it’s normal to make a few spelling mistakes here and there - it just means you’re human."

Fortunately, we can fix this with JavaScript by using a regular expression and the replace() method:

const textBlockCorrected = textBlock.replace(/-/g, "—")

console.log(textBlockCorrected)
// "When you’re typing fast it’s normal to make a few spelling mistakes here and there — it just means you’re human."

Does it look the same? Trust me, it’s not. Look closer. Or try printing out the result of textBlock and textBlockCorrected that makes it easier to see the difference:

console.log(textBlock)
//"When you’re typing fast it’s normal to make a few spelling mistakes here and there - it just means you’re human."

console.log(textBlockCorrected)
// "When you’re typing fast it’s normal to make a few spelling mistakes here and there — it just means you’re human."

Note: in typography, it’s a lot easier to tell the difference between letters and symbols when the font used is not a monotype like the one we use for code examples (the font called Menlo). But I’ll save the details about em, en, and hyphens for a typography oriented tutorial.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on