0

I'm currently developing a simple web app using html with JavaScript, and I'm trying to do a simple string.replace call on a string received from a html textarea like so;

var contents = document.getElementById("contents").value;
var alteredText = contents.replace(/£/g, "poundsign");

The problem is that when a £ sign is included in the string, the replace call can't find it. I've looked at the code via the console and it seems that anytime there's a $ sign in JavaScript it adds a "Â" to the £ symbol, so

string.replace(/£/g, "poundsign");

as it was written in the js file becomes the following while running:

string.replace(/£/g, "poundsign");

while £ in var contents remains simply £ (putting £ into the textarea causes the replace call to work correctly). Is there a way to stop the  being added in the js file, or to add it to the html file before .replace is called?

The  is added anytime £ appears in the js file as far as I can see, and I haven't been able to get it to match up with the html without the user adding the  to the html themselves.

  • string.replace(/£/g, "poundsign"); are you targeting variable var_string.replace ? Also why are you doing "/£/g" why not just "£" ? there's no need to Regex it ? – Riddell May 04 '16 at 10:33
  • 1
    Can you check this link out? http://stackoverflow.com/questions/280712/javascript-unicode-regexes – David Guan May 04 '16 at 10:33
  • possible dup? http://stackoverflow.com/questions/4382518/why-cant-i-display-a-pound-%C2%A3-symbol-in-html – ste2425 May 04 '16 at 10:34
  • @Riddell there might be multiple occurrences of "£", so we need to add /g option, and for that we need to use Regex. – Mohit Bhardwaj May 04 '16 at 10:43
  • @Mike I see, well thanks for information Mike! – Riddell May 04 '16 at 10:45

2 Answers2

0
   // replace pound string by empty string
   var mystr = '£';
   mystr = mystr.replace(/£/g,'poundsign');
   alert(mystr);
Khalid Habib
  • 1,100
  • 1
  • 16
  • 25
0

Thanks to @David Guan for the link, that put me on the right track, and to everyone else that commented.

The issue was resolved when I used the Unicode number in the .replace call rather than the character, it was able to then match the £ sign correctly without the  also being inserted.