JavaScript replace() function has limitation. Simple characters can easily be replaced but What if we’re concerned with a pattern instead? The replace() method used with RegEx can achieve this.
Example replace with regex in JavaScript
Simple example code use RegEx, the first argument of replace
will be replaced with regex syntax, for example /regex/
.
The .replace()
returns a new string, and the original remains the same. The .replace()
will only replace the first matched pattern it finds unless use regex with the g
flag to replace all matches.
<!doctype html>
<head>
<script>
const str = '1 paidCodeCamp paid';
const res1 = str.replace('paid', 'free');
const res2 = str.replace(/paid/g, 'free');
console.log(res1);
console.log(res2);
</script>
</head>
<body>
</body>
</html>
Output:
Replace special characters from a string
let str = "Javascript123 #* Is The &^ Most Popular Language";
var res = str.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
console.log(res);
Output:
Javascript123 Is The Most Popular Language
Replace spaces from a string
dummyString.replace(/\s+/g, '');
Replace anything but digits from a string
dummyString.replace(/[^0-9]/g,'');
Understand:
- /and / marks the beginning and end of a pattern
- [^0-9] matches all characters except digits within the string.
- g specifies to match all occurrences of the pattern within the string.
- \s+ matches at least one space character within the string.
- [ ] finds the characters within the brackets
- `~!@#$%^&*()_|+-=?;:’”,.<>{}[]\\/ matches these special characters within the string
Do comment if you have any doubts or suggestions on this JS replace topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version