Extract a specific word from a string in JavaScript

I have a URL with a query string that starts and ends with specific letters. Here is an example and my approach:

Say the address in the address bar "http://localhost:3001/build/?videoUrl=bitcoin.vid.com/money#/"

First I retrieve this url with window.location.hrefand save it in a variable x.

Now I want to check first whether videoUrlthe URL is present or not, and then if it is available, I split the URL and retrieve the required URL, whichbitcoin.vid.com/money

let x = "http://localhost:3001/build/?videoUrl=bitcoin.vid.com/money#/";
let y;
let result;
if(x.indexOf("?videoUrl")>-1) {
   y = x.split("?videoUrl=");
   result = y[1].split("#")[0];
   console.log("Resultant URL:", result);
}

I feel that all the code I wrote is a bit cumbersome. Can someone tell me if there is a more elegant way to do the same?

Note. videoUrlalways unavailable in the url so check if it exists. And please also let me know if I need to do any checks?

.

+4
2

, thing-, JavaScript URL().

let x = "http://localhost:3001/build/?videoUrl=bitcoin.vid.com/money#/";
console.log((new URL(x)).searchParams.get("videoUrl"));
Hide result

videoUrl , null,


, , , :

const getParamFromUrl = (url, param) =>
    (new URL(url)).searchParams.get(param);

, : https://developer.mozilla.org/en-US/docs/Web/API/URL

+11

!

:

  • URL, @Lissy, , , . , corss
  • Alternativley, , . (\?|\&)([^=]+)\=([^&]+) - ,
+1

Source: https://habr.com/ru/post/1691757/


All Articles