Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Replace multiple instances of text surrounded by specific characters in JavaScript?
Let's say we have a string where certain text is surrounded by special characters like hash (#). We need to replace these placeholders with actual values.
var values = "My Name is #yourName# and I got #marks# in JavaScript subject";
We need to replace the special character placeholders with valid values. For this, we use replace() along with shift().
Using replace() with shift()
The replace() method with a regular expression can find all instances of text surrounded by hash characters. The shift() method removes and returns the first element from an array, making it perfect for sequential replacements.
var values = "My Name is #yourName# and I got #marks# in JavaScript subject"; const originalValue = ["David Miller", 97]; var result = values.replace(/#([^#]+)#/g, _ => originalValue.shift()); console.log(result);
My Name is David Miller and I got 97 in JavaScript subject
How It Works
The regular expression /#([^#]+)#/g breaks down as:
-
#- matches the opening hash character -
([^#]+)- captures one or more characters that are not hash -
#- matches the closing hash character -
g- global flag to replace all matches
Alternative Method Using Object Mapping
For more control over which values replace which placeholders, you can use an object:
var values = "My Name is #yourName# and I got #marks# in JavaScript subject";
const replacements = {
yourName: "David Miller",
marks: 97
};
var result = values.replace(/#([^#]+)#/g, (match, key) => replacements[key]);
console.log(result);
My Name is David Miller and I got 97 in JavaScript subject
Comparison
| Method | Pros | Cons |
|---|---|---|
| Array with shift() | Simple, sequential replacement | Order-dependent, modifies original array |
| Object mapping | Named placeholders, reusable | Requires matching key names |
Conclusion
Use replace() with regular expressions to replace text surrounded by special characters. The array method works well for sequential replacements, while object mapping provides better control for named placeholders.
