Search code examples
javascriptstringcasperjsstringify

CasperJS cannot obtain IP without other useless data


I have now update the CasperJS script see below

var casper = require('casper').create();

casper.start('http://whatismyipaddress.com/', function() {
    if (this.exists('#section_left > div:nth-child(2)')) {
        var data = this.getElementInfo('#section_left > div:nth-child(2)');
        console.log(JSON.stringify(data.text));
    }
});

casper.run();

How to I remove the " and \n and \t from the result I get below.

"\n\n23.221.147.202\n\n\t\t\t\t\t"

Solution

  • data.text is a single string. Stringifying a string leads to escaping whitespace and addition of quotation marks. Don't stringify a string:

    console.log(data.text);
    

    If you actually want to remove the whitespace, there is the string function trim():

    console.log(data.text.trim());