|
| 1 | +// 15. Replace Characters of a String |
| 2 | + |
| 3 | +// JavaScript Program to Replace Characters of a String |
| 4 | + |
| 5 | +// 1. Using map() & split() method to replace characters from String |
| 6 | + |
| 7 | +{ |
| 8 | + const str = "Hello user, welcome to GeeksforGeeks"; |
| 9 | + let oldWord = "Hello"; |
| 10 | + let newWord = "Hi"; |
| 11 | + const replaceString = str |
| 12 | + .split(" ") |
| 13 | + .map((word) => (word === oldWord ? newWord : word)) |
| 14 | + .join(" "); |
| 15 | + console.log(replaceString); |
| 16 | +} |
| 17 | + |
| 18 | +// Using String replace() Method to replace characters from String |
| 19 | + |
| 20 | +{ |
| 21 | + const str = "Welcome to GFG"; |
| 22 | + const replStr = "GFG"; |
| 23 | + const newStr = "Geeks"; |
| 24 | + |
| 25 | + const updatedStr = str.replace(replStr, newStr); |
| 26 | + |
| 27 | + console.log(updatedStr); |
| 28 | +} |
| 29 | + |
| 30 | +// Using Regular Expression to replace characters from String |
| 31 | + |
| 32 | +{ |
| 33 | + const str = "Welcome to GeeksforGeeks"; |
| 34 | + const searchString = "Welcome"; |
| 35 | + const replaceString = "Hello"; |
| 36 | + let regex = new RegExp(searchString, "g"); |
| 37 | + let replacedString = str.replace(regex, replaceString); |
| 38 | + console.log(replacedString); |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +// Using split and join Method to Replace Characters from a String |
| 43 | + |
| 44 | +{ |
| 45 | + |
| 46 | + const str = "welcome to gfg"; |
| 47 | + const oldStr = "gfg"; |
| 48 | + const newStr = "Geeks"; |
| 49 | + const updatedStr = str.split(oldStr).join(newStr) |
| 50 | + |
| 51 | + |
| 52 | + console.log(updatedStr); |
| 53 | + |
| 54 | +} |
0 commit comments