Lukas Naujokaitis
Lukas Naujokaitis

Reputation: 421

How to use lastIndexOf() function with symbols

Just started using indexOf() and lastIndexOf() functions and I know why they are used, however, the result doesn't make me feel happy :)

let str = $('#info').html();

// WORKS
//alert(str.lastIndexOf('√'));

// DOESN'T WORK
alert(str.lastIndexOf('√'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">&#x0221A;</div>

The problem is I get the alert result as "-1", which means the &#x0221A; couldn't be found in the str variable. Using simple symbol it works, however, I'm not sure if it's a good practice using this symbol here.

In my opinion, another approach about this problem would be encoding symbol in the HTML to &#x0221A;, so using "Inspect element" feature you would see &#x0221A;.

What do you think?

Upvotes: 3

Views: 144

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

When the browser reads and parses your HTML, it builds up a DOM, without retaining the exact HTML you provided. Later, if you ask for HTML, it builds a new HTML string using its own rules for doing that.

That's why str.lastIndexOf('&#x0221A;') doesn't work: The browser isn't under any obligation to give you back the character in the same form you used when you supplied it. It could give it back as just a character () or a named character reference (&radic; in this case) or a decimal numeric character reference (&#8730;), rather than the hex numeric character reference you're looking for.

You'll have to test on your target browsers to see what they give you, and then look for that. I suspect most if not all will return the actual character, and so your str.lastIndexOf('√') (or str.lastIndexOf('\u221A')) will be the way to go.

<div>&radic;</div>

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

There is no direct way to achieve this. But if you still want to do this way then you simply need to create a HEX value of the ASCII value:

let str = ascii_to_hexa($('#info').html());
str = '&#x0'+str.toUpperCase()+';';

alert(str.lastIndexOf('&#x0221A;'));

function ascii_to_hexa(str)
{
  var arr1 = [];
  for (var n = 0, l = str.length; n < l; n ++){
    var hex = Number(str.charCodeAt(n)).toString(16);
    arr1.push(hex);
  }
  return arr1.join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">&#x0221A;</div>

Upvotes: 3

Related Questions