0

i was manipulating the text in this document http://www.dlib.org/dlib/november14/brook/11brook.html, while i noticed something strange. I was looking at the beginning of the article, in particular here:

Michelle Brook
The Content Mine
[email protected]
...

(I am using jquery xpath)

var string=$("document").xpath("form[1]/table[3]/tr/td/table[5]/tr/td/table[1]/tr/td[2]/p[2]").html();
var new_string=string.substring(0,14);

I would expect that new_string was "Michelle Brook", but it was "Michelle Bro". Why that? Is there a particular char that makes string.substring() fail?

13
  • 3
    Why don't you console.log() the string before you call .substring() and see what it really contains? Commented Jan 25, 2016 at 15:32
  • 1
    I suspect there are several sequential instances of whitespace that gets collapsed when rendered, but still exist in the source string. Commented Jan 25, 2016 at 15:33
  • 1
    for(var x=0;x<14;x++) console.log(string.CharAt(x)); Commented Jan 25, 2016 at 15:37
  • 1
    @RobertMcKee I think you're thinking of .charCodeAt() Commented Jan 25, 2016 at 15:43
  • 1
    Well, there is your answer. You have a linefeed as your first character. I'm guessing .charCodeAt(1) is also another odd character (10,13,or 8206) Commented Jan 25, 2016 at 15:53

1 Answer 1

1

Use the following to remove all leading and trailing whitespace from your string before trying to substring it:

var new_string=string.replace(/^\s*/, '').replace(/\s*$/, '').substring(0,14);
Sign up to request clarification or add additional context in comments.

7 Comments

I have understand the problem: does your code delete all character that can make substring() fail?
substring isn't failing.
using that replace, in different parts of the document i can see some &nbsp; word: why? how can i delete them?
I would suggest using an HTML parser instead of trying to use XPATH to parse your document.
string.trim().substring(0,14); is shorter
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.