Ad

Javascript Substring Doesn't Return The Correct String

- 1 answer

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?

Ad

Answer

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);
Ad
source: stackoverflow.com
Ad