How to use JavaSccript reduce() Method and spread operator In Javascript
We can use the spread operator to make an array from the character of a string and form a string with the help of reduce() method without dots in the string.
Syntax:
[...str].reduce( (accum, char) => (char==='.') ? accum : accum + char , '')
Example: In this example, we will replace ( ‘.’ ) by using the spread operator and reduce function.
// Assigning a string
let str = "Geeks.for.Geeks";
// using reduce(), and sprea operator
let newStr = [...str].reduce(
(s, c) => (c === "." ? s : s + c),""
);
// Printing original string
console.log("String 1: " + str);
// Printing replaced string
console.log("String 2: " + newStr);
Output
String 1: Geeks.for.Geeks String 2: w3wiki
How to replace all dots in a string using JavaScript ?
We will replace all dots in a string using JavaScript. There are multiple approaches to manipulating a string in JavaScript.
Table of Content
- Using JavaScript replace() Method
- Using JavaScript Split() and Join() Method
- Using JavaSccript reduce() Method and spread operator
- Using JavaScript replaceAll() Method
- Using JavaScript for loop
- Using JavaScript map() Method on Arrays
Contact Us