Вопрос

I am trying to get a string from a html page with jquery and this is what I have.

var text = $(this).text();

var key = text.substring(0,1);
if(key == ' ' || key == ' ')
    key = text.substring(1,2);


text is this  Home

And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!

Это было полезно?

Решение 2

If you want remove spaces at the beginning (and end) of a string, you can use the trim function

var myvar = " home"
myVar.trim() // --> "home"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Другие советы

There are several problems with the code in the question. First,   has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.

Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what   means in HTML; it is not an Ascii character, by the way), then the following code would work:

var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
   text = text.substring(1, text.length);
}

The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.

Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top