Emerson Jones
Emerson Jones

Reputation: 11

Replace a string in nodejs, example id: with _xid:

I need to replace all id: from a string to _xid: tried, use

string.replace (/id:/g, '_xid:')

but it doesn't work.

Upvotes: 0

Views: 259

Answers (3)

sahil khaire
sahil khaire

Reputation: 79

let text = 'first id: and second id:'
text = text.replace(/id:/g, '_xid:');
console.log(text)

Upvotes: 0

Shachar
Shachar

Reputation: 54

string.replace(/id:/g, '/_xid:/') can't find anything as the '/' chars are considered the opening and closing of a regex.

Try

str.replace(/\/id:\//g, '/_xid:/')

to escape '\' char.

Upvotes: 0

btnhawk
btnhawk

Reputation: 231

Try this:

String.prototype.replaceAll = function (search, replacement) {
    const target = this
    return target.replace(new RegExp(search, 'g'), replacement)
}

string.replaceAll('id', '_xid')

Upvotes: 1

Related Questions