Home > front end >  For loop for splitting a url through '?'
For loop for splitting a url through '?'

Time:11-05

I have a variable url, which has the following value: 'https://xxx?yyy?zzz'

Through a for loop, I am trying to split the url into : - https://xxx - yyy - zzz

I do that division thanks to the .split(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) method.

So, what I have is the following:

let url = https://xxx?yyy?zzz;

if(url.includes("?")) { 
      for(var i = 0; i <= url.split("?").length; i  ) {
          urlTotal = url.split("?")[i]   '?'
      }
}

What I would like to do is to join the first two parts of the url, like this: https://xxx?yyy.

But I also have to keep in mind that if the url has, for example, 5 '?', I have to take the first four parts.

For example: let url = https://xxx?yyy?zzz?jjj?hhh

The result, should be the following: https://xxx?yyy?zzz?jjj

Thank you.

CodePudding user response:

let url = 'https://xxx?yyy?zzz?jjj?hhh';
console.log(url.includes('?')?url.split('?').slice(0,-1).join('?'):url);

Alternatively, use lastIndexOf:

let url = 'https://xxx?yyy?zzz?jjj?hhh';
console.log(url.includes('?')?url.substring(0,url.lastIndexOf('?')):url);

CodePudding user response:

let str1 = `https://xxx?yyy?zzz`
let str2 = `https://xxx?yyy?zzz?jjj?hhh`
let str3 = `https://stackoverflow.com/`

const parse = (url) => {
   if(url.indexOf('?') == -1){
     return url
   }
   let strs = url.split('?')
   strs = strs.slice(0,strs.length-1)
   return strs.join('?')
}

console.log(parse(str1))
console.log(parse(str2))
console.log(parse(str3))

  • Related