Satheesh
Satheesh

Reputation: 902

Replace special characters in JavaScript

How to replace '$txt$' in javascript.I want to replace all occurrences in the string

It's what i tried

if (html.indexOf('$txt$') > -1) {
    html = html.replace(/$txt$/ig, '<input type=text></input>');
}

but it won't replace the string.What's my mistake.Please help me

Upvotes: 0

Views: 2030

Answers (3)

Barney
Barney

Reputation: 16466

You're replacing using regular expressions, and $ is a regular expression reserved special character for end of line/string.

You need to escape the $ by preceding it with a backward slash \ to make it hit its literal character:

if (html.indexOf('$txt$') > -1) {
    html = html.replace(/\$txt\$/ig, '<input type=text></input>');
}

Upvotes: 0

Nagaraju Badaeni
Nagaraju Badaeni

Reputation: 900

html = html.replace(/[$]txt[$]/ig, ''); use this

Upvotes: 0

Daniel van Dommele
Daniel van Dommele

Reputation: 550

all you need to do is escape the $ sign since it has a meaning in a regular expression. Change it to

html = html.replace(/\$txt\$/ig, '<input type="text" />');

and it should be fine :)

edit: $ means end of line in a regular expression :)

Upvotes: 8

Related Questions