JS String Substitution
In this article, we will see what is JS string substitution and how to use it.
What is string substitution?
String substitution in javascript is the replacement of a specific substring in a string with another value. Even if we merge one string value with another, it is treated as a substitution. We mostly use the ‘replace()’ method to perform string substitution in javascript.
For example:
We have the string “John went to the store and bought a cookie”, if we change the substring “cookie” to “chocolate“, we get “John went to the store and bought a chocolate”.
4 ways to string substitution
In JavaScript, there are three ways to string substitution:
1. Using replace() method
In this method, we can replace the particular substring. We should pass two arguments in the ‘replace()‘ method. In the first argument, we have to give the substring we want to replace and in the second argument, we have to give the value or substring we want to replace it. So, let’s see both examples:
Replace first occurrences substring
If the substring repeats multiple times, then only the first occurrence of the substring is replaced. For example, the following code replaces only the first occurrences of the substring “fox” with the substring “cat”.
let str = "The quick brown fox jumps over the lazy fox.";
let newStr = str.replace("fox", "cat");
console.log(newStr);
//Output : The quick brown cat jumps over the lazy fox.
- In this above example, we have declared the string ‘str’.
- Then we created the variable ‘newStr’ and replaced the first occurrence of the substring “fox” with the substring “cat”. So, we passed, the first argument as ‘fox’ and the second as ‘cat’.
- Then we logged the ‘newStr’. We got an output “The quick brown cat jumps over the lazy fox.”, the word ‘fox’ was successfully replaced with ‘cat’.
Replace all occurrences substring
If you want to replace all occurrences substring, you need to use regular expression with global flag. For example, the following code replaces all occurrences of the substring “cat” with the substring “dog”.
let str = "The cat jumps over the lazy cat.";
let newStr = str.replace(/cat/g, "dog");
console.log(newStr);
// Output: The dog jumps over the lazy dog.
- In this example, we pass the first argument of replace() method as the regular expression ‘/cat/g’ and the second argument as ‘dog’.
- If it matches all occurrences of the substring “cat” within the string, and the replace() method replaces each occurrence with the substring “dog”.
- We got an output, ‘The dog jumps over the lazy dog.’, the two words ‘cat’ was successfully replaced with ‘dog’.
2. Using template literals
This method, allows you to embed expressions inside strings using the ‘${}‘ syntax. It is easy to perform substitutions within a string, without concatenating multiple strings or variables. Let’s see an example:
let name = "student";
let age = 'computer science';
let msg = `My name is ${name} and I'm ${age} years old.`;
console.log(msg);
// Output: My name is John and I'm 30 years old.
- In this example, we have declared two variables ‘name’ to ” and ‘age’.
- Then we created the variable ‘msg’. We use a template literal to create a string that includes the variable’s name and age within the string using the ‘${}‘ syntax. The values of the variables are automatically substituted in the resulting string when the template literal is evaluated.
- Then we logged ‘msg’. Finally, we got the output, “My name is John and I’m 30 years old”.
- The variables ‘name’ and ‘age’ are inserted successfully into the ‘msg’.
3. Using replaceAll method
The ReplaceAll() method is a new addition to ECMAScript 2021. We can allow replacing all occurrences of a specified string with another string using the ‘replaceAll()’ method. This method is also similar to the regular expression with replace() method. For example:
const sentence = "We drink coffee every morning";
const newSentence = sentence.replaceAll("coffee", "tea");
console.log(newSentence);
// Output: We drink tea every morning.
- In this example, we use ‘replaceAll()’ method and pass the first argument as ‘coffee’ and the second argument as ‘tea’.
- The word ‘coffee’ will be replaced with ‘tea’ successfully.
4. Using String concatenation
The ‘+’ plus symbol operator indicates the string concatenation. You can include variables or literals within the string by concatenating them to the rest of the string.
var name = "John";
var age = 24;
console.log("My name is " + name + " and I am " + age + " years old.");
// Output: My name is John and I am 24 years old.
- In this above example, we have declared the variable ‘name’ to ‘john’ and ‘age’ to ’24’.
- Then we logged the variable ‘name’ and ‘age’ into a string using the ‘+’ concatenation operator.
Concatenation can be used for JS string substitution, which can get complicated when dealing with complex strings or many variables. In these cases, it’s easier to use template literals or the replace() method.
Benefits of using string substitution
The main benefits of using string substitution in JavaScript are:
- Readability: String substitution can make the code easier to read and understand, especially when dealing with large strings or complex expressions.
- Flexibility: We can easily construct dynamic strings that change based on runtime conditions or user input.
- Efficiency: String substitution is often more efficient than concatenating strings manually, especially when working with complex strings that contain many variables or expressions.
Conclusion
So, these are the various ways to sting substitution in Javascript. I recommended the ‘replace’ method.