3

I'm attempting to find the index of the first space in a string from an element's html. In a test case where I simply set a test variable and check the indexOf(' '), it shows up.

For example, the following results in test having a length of 11 characters with the first space at the 5th position, as it should.

var test = 'hello there';
var idxTest1 = test.indexOf(' ');

However, if I set my test variable to a .text() value from a jQuery elements .html(), I'm getting a -1 for the index of the space even when test still appears to be equal to 'hello there' with a length of 11 characters.

What's going on here? http://jsfiddle.net/jhuTB/

6
  • Can you show your HTML? It should work. Commented Jan 8, 2014 at 10:07
  • 1
    @putvande see jsfiddle -- i.imgur.com/CVRaVgs.png Commented Jan 8, 2014 at 10:08
  • How about $(test).toString().indexOf(' ')? Commented Jan 8, 2014 at 10:13
  • 1
    I found hex value for space character is '20' for 'test' and 'A0' for 'test2'. I don't know why but it may help. Commented Jan 8, 2014 at 10:15
  • 1
    .split(/\s/).join(' ') will work. Issue is on encoding space character i guess jsfiddle.net/jhuTB/2 Commented Jan 8, 2014 at 10:15

3 Answers 3

2

Watch out,   the "non breaking space" is not the typical space from the space-bar. When watching ascii characters the space from the space bar is ASCII 32 (0x20) while the nbsp is ASCII 160 (0xA0) hence the inequality.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha, that's it. var idxTest2 = test2.indexOf('\u00A0'); results in 5. Good call.
0

try something like this

$(function(){
    var test2 = $('#test').html();
    var idxTest1 = test2.indexOf('\u0026');
    console.log(idxTest1);
})

if using text() than try

$(function(){
    var test2 = $('#test').text();
    var idxTest1 = test2.indexOf(String.fromCharCode(160));
    console.log(idxTest1);
})

Comments

0

Use str.charCodeAt(index) to check the difference:

var test = 'hello there';
var test2 = $("<div/>").html($('#test').html()).text();
console.log(test.charCodeAt(5));  // 32
console.log(test2.charCodeAt(5)); // 160

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.