Replace All Characters in a JavaScript String with Regular Expressions
Question details
Replace or remove every occurrence of a character in a JavaScript string using a regular expression.

- Product
- JavaScript
- Device & OS
- not provided
- Scenario
- A developer wants to remove spaces or special characters throughout a string.
- Observed behavior
- A global regular expression can match every occurrence, while special regex characters must be escaped to match them literally.
Identify the character you want to replace and whether it has a special meaning in regular expressions. Decide whether to remove it with an empty string or replace it with another value.
Use a Global Regular Expression with String.replace
Use this approach to replace every match in a JavaScript string, including literal periods or dollar signs.
In your JavaScript code, use the global flag and assign the result: var strng = "George Smith Patton"; strng = strng.replace(/ /g, "");. The result is "GeorgeSmithPatton".
To remove periods, use strng = strng.replace(/\./g, "");. To remove dollar signs, use strng = strng.replace(/\$/g, "");. The backslash makes each character a literal match.
To replace rather than remove a character, put the replacement text in the second argument. For example, strng.replace(/ /g, "-") replaces every space with a hyphen.

Replace Characters in a Document with WPS Writer
If you need to replace characters in document text rather than execute JavaScript, use WPS Writer's Find and Replace tool.
- 1. Open your document: Open the document containing the text in WPS Writer.
- 2. Open Replace: Press Ctrl+H or open Find and Replace from the editing tools.
- 3. Enter the text: Enter the character in the Find field. Enter replacement text in the Replace field, or leave it empty to remove the character.
- 4. Replace all matches: Select Replace All and review the updated document.

Frequently Asked Questions
Why does replace remove only the first occurrence?
A regular expression without the global flag stops after the first match. Add g, as in strng.replace(/ /g, ""), to replace every match.
Why do I need to escape a period or dollar sign?
In a regular expression, a period normally matches any character and a dollar sign marks the end of a string. Use /\./g or /\$/g to match the literal character throughout the string.
Does replace change the original string?
No. JavaScript strings are immutable, so assign the result to a variable, such as strng = strng.replace(/ /g, "").
Will replacing a string update text on a web page?
Not automatically. After creating the new string, assign it to the relevant element's textContent if you want to update displayed plain text.




