How to replace all occurrences of a character in a string in JavaScript
In this tutorial, we will learn how to replace all occurrences of a character in a string in JavaScript. String references in Javascript are immutable. This means that once a String object is assigned to a String reference(variable), the value of the object cannot be changed.
Replace all occurrences of a character in a string in JavaScript
Variables used in the code
- str – string
- searchChar – replaced character
- replaceChar – replacing character.
let str = "This is a Tutorial in CodeSpeedy" let searchChar = 'i' let replaceChar = 'a'
Method 1
This method focuses on replacing all occurrences of a character in a string (case-insensitive).
Inbuilt Functions usedÂ
- indexOf() – returns the index of the substring in a string.
- slice() – returns the substring of the string.
- toLowerCase() – returns the lowercase of the string.
- toUpperCase() – returns the uppercase of the string.
Here we are finding the index of searchChar in the string str. while the index is not -1, then the searchChar is in the string(str) and we are replacing the character with replaceChar, else we will return the same string str.
function ReplaceAll(str,searchChar,replaceChar){ while(str.toLowerCase().indexOf(searchChar.toLowerCase())!== -1){ let index = str.toLowerCase().indexOf(searchChar.toLowerCase()) if(str[index] === str[index].toUpperCase()){ str = str.slice(0,index)+replaceChar.toUpperCase()+str.slice(index+1,) } else{ str = str.slice(0,index)+replaceChar.toLowerCase()+str.slice(index+1,) } } return str; }
Method 2
This method focuses on replacing all occurrences of a character in a string (case-sensitive).
Inbuilt Functions used
- split() – splits a string into an array of substrings
- join() – joins an array of substrings to a string.
Here we are splitting the string by searchChar and joining the substring array with replaceChar
function ReplaceAll(str,searchChar,replaceChar){ let substrings = str.split(searchChar) return substrings.join(replaceChar) }
str = ReplaceAll(str,searchChar,replaceChar) console.log(str)
Output
Thas as a Tutoraal an CodeSpeedy
Leave a Reply