How to Replace Commas in a String in JavaScript
-
Use the
replace()
Method to Replace Commas in a String in JavaScript - Replace Commas in a String Using JavaScript
We will learn in this article how to use the replace()
method to replace all commas in a string using JavaScript.
Use the replace()
Method to Replace Commas in a String in JavaScript
The replace()
is a pre-defined method, and we use it on strings to replace the defined portion of that string with another. It searches the defined string portion from the complete declared string and replaces it with the given value.
The original string does not change by the replace()
method, returning the updated string.
Code:
<script>
let string = "Delft stack is a good website to learn programming"
let result = string.replace("good","best")
console.log("original string: "+string)
console.log("updated string: "+result)
</script>
Output:
"original string: Delft stack is a good website to learn programming"
"updated string: Delft stack is a best website to learn programming"
We initialized a string containing the word "good"
and used the replace()
method on that string with 2 arguments replace("good","best")
.
It will find the "good"
word in the string and replace it with "best"
.
Replace Commas in a String Using JavaScript
Only the first found string portion will be replaced if you only replace a value. We use a regular expression with the modifier set (g) to replace all instances.
To replace commas from the string, we need a string that contains a comma(s). Like the above example, we use the replace()
method to replace all commas like replace( /,/g , "other string or space" )
.
Code:
<script>
let string = "Delft,stack,is,a,best,website,to,learn,programming"
let resultSingle = string.replace(","," ") //replace single
let resultAll = string.replace(/,/g," ") //replace all
console.log("Original string: "+string)
console.log("Replace single: "+resultSingle)
console.log("Replace All: "+resultAll)
</script>
Output:
"Original string: Delft,stack,is,a,best,website,to,learn,programming"
"Replace single: Delft stack,is,a,best,website,to,learn,programming"
"Replace All: Delft stack is a best website to learn programming"
In the above code, we first have an initialized string containing commas. Then, we’ve applied the replace()
method to replace a single coma from string using replace(",","")
.
We used the replace()
method on that string containing the regular expression /,/g
to replace all the comas. We have printed the log for the original string and updated strings.