Radiant
Radiant

Reputation: 41

How do i replace all occurences of a substring with another substring in a string?

I tried

str = "sampletext11111111"
str.replace("1","a")
console.log(str)

The result it gives is

sampletexta1111111

please help

Upvotes: 1

Views: 141

Answers (2)

Abion47
Abion47

Reputation: 24746

Use replaceAll:

let str = "sampletext11111111"
str = str.replaceAll("1", "a")
console.log(str)

Upvotes: 2

eol
eol

Reputation: 24565

You can supply a regex and use the global modifier:

let str = "sampletext11111111"
str = str.replace(/1/g,"a")
console.log(str)

Upvotes: 0

Related Questions