0

I have some html buttons with a value contains html entities. For example

<input  type="button" name="sin" value="sin&#178;" onClick="insertChar(this)">
<input  type="button" name="cos" value="cos&#178;" onClick="insertChar(this)" >
<input  type="button" name="plus" value="+" onClick="insertChar(this)" >

values of these button is concated to a value of textarea in the html form. Suppose the value of textarea is "sin²+cos²". Now I want to replace the html entity &#178 with a char "2". I tried with this javascript code

String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
    var _token;
    var str = this + "";
    var i = -1;
    alert(token+"----------------------");
    if ( typeof token === "string" ) {

        if ( ignoreCase ) {

            _token = token.toLowerCase();

            while( (
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }

        } else {
            return this.split( token ).join( newToken );
        }

    }
return str;
};

The above code is working fine for replacing a character with another character, but it is not working for replacing a html entity with a char.

  • Nitpicking I know, but you should put a semicolon at the end of your character entity references like so: `²` – david Jan 15 '14 at 06:42
  • @david I forgot to put a semicolon here, in my code I wrote the semi colon. when I call the function with the values replaceAll('²', '2', true). It is showing the token as ² instead of ² – Venkata Aditya Pavan Jan 15 '14 at 06:52
  • possible duplicate of [HTML Entity Decode](http://stackoverflow.com/questions/5796718/html-entity-decode) – Lars Ebert Jan 15 '14 at 06:54

1 Answers1

0

There are no HTML entities to replace in the string, when JavaScript code gets at it. Simply replace the character “²” denoted by the entity:

replaceAll('²', '2')

If you do not know how to enter “²” (copy and paste would do, really) or how to specify the character encoding of the file containing the code, you can use a JavaScript escape notation for the character:

replaceAll('\u00B2', '2')

The point is that HTML entities are parsed by HTML parser of the browser, and in this process, before any JavaScript execution, they are replaced by the characters they denote. You can see this if you display, in this case, the value of the value property of an element.

(I don’t see why you would change the expression sin² to something less correct, but this would be the way to do that.)

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390