replace a character in a string in javascript

To replace a character in a string in JavaScript, you can use the replace() method. This method replaces a specified value with another value in a string.

Here's an example to replace the first occurrence of a character in a string:

index.tsx
let str = "hello world";
let newStr = str.replace("l", "x"); // Replaces the first "l" with "x"
console.log(newStr); // Output: "hexlo world"
142 chars
4 lines

Note that the replace() method only replaces the first occurrence of the specified value. If you want to replace all occurrences, you can use a regular expression with the global flag:

index.tsx
let str = "hello world";
let newStr = str.replace(/l/g, "x"); // Replaces all "l" with "x"
console.log(newStr); // Output: "hexxo worxd"
137 chars
4 lines

In the second example, /l/g is a regular expression with the global flag g that matches all occurrences of the letter "l". The method then replaces all matches with the letter "x".

related categories

gistlibby LogSnag