Home > Net >  get domain substring using javascript
get domain substring using javascript

Time:12-16

I am trying to parse a domain that has more than two period's in the string.

So for example, I am trying to get sjmktmail-batch1a.marketo.org into marketo.org

I tried using split and a range from the list like this:

testdata = sjmktmail-batch1a.marketo.org
testdata.split(".")[1:2]

but that didn't work. doing testdata.split(".")[1] brings up marketo but I want marketo.org

Sorry, my main language is python, so some javascript concepts confuse me. I assume you can't get a range of an array/list by using [x:x]

My main goal is to get a domain like domain.com

so for example:

fdasdadio.conglomo.com would be conglomo.com billy.fdaoco.codsaso.mainbug.com would be mainbug.com purple.red.bri.noschool.edu would be noschool.edu

Pretty sure I am missing a concept that would make this easy.

CodePudding user response:

You can do it by a chain of split, slice, join. like this:

slice(-2) means get two last items from array.

const str = 'billy.fdaoco.codsaso.mainbug.com';
const domain = str.split('.').slice(-2).join('.');
console.log(domain)

CodePudding user response:

One line code:

"sjmktmail-batch1a.marketo.org".split('.').slice(1).join('.')

    const input = "sjmktmail-batch1a.marketo.org";
    var data =input.split('.')      // ["sjmktmail-batch1a", "marketo", "org"]
    data = data.slice(1);           // ["sjmktmail-batch1a"]
    const output = data.join('.');  // "marketo.org"
    console.log(output);

CodePudding user response:

It's as easy as splitting the string, and getting the last two elements of the string, right?

var str = "sjmktmail-batch1a.marketo.org"
var arr = str.split(".");
console.log(arr[arr.length-2] "." arr[arr.length-1])

  • Related