1

I have a querystring:

window.location.search
?myvar=kx

How would I slice off the '?' at the beginning? For example, in python I would do either:

str = str.lstrip('?')

or

str = str[1:]

How would I do either of those in javascript?

  • use `.split()` like `str.split('?')` what is your aim for doing this? – guradio Oct 24 '18 at 00:34
  • Possible duplicate of [Delete first character of a string in Javascript](https://stackoverflow.com/questions/4564414/delete-first-character-of-a-string-in-javascript) – Raymond Chen Oct 24 '18 at 00:37

3 Answers3

2

You may use split if you want to get left or right after slicing:

var loc = "http://test.com?myVar=kx&myCar=BMW";
var res = loc.split("?");
var url = res[0]
var params = res[1]

If you want to get URL without queryString, you can try following:

var loc = window.location; // or new URL("http://test.com?myVar=kx&myCar=BMW");
var url = loc.origin;

If you want to get value of parameter in URL then you may use URLSearchParams which is quite simple and easy.

let params = new URLSearchParams(window.location.search);
let myVar = params.get('myvar');

You can also use it like this:

let params = new URL('http://test.com?myVar=kx&myCar=BMW').searchParams;
params.get('myVar'); // "kx"
params.get('myCar'); // "BMW"

If this is not what you want, you can try regex or other string operation which help you in finding what you want. You can check at w3schools

M.G.
  • 44
  • 5
0

For the substring you can do the following:

str.substring(1)

For the lstrip you could use regex.

0

If you are looking to specifically get everything after the beginning query, I would do something like the function below.

// function you can use:
function getQueryString(str) {
  return str.split('?')[1];
}
// use the function:
console.log(getQueryString("?myvar=kx")); // which returns 'myvar=kx'
schmitty890
  • 175
  • 2
  • 7