Thats my code:
const searchTerm = `?term=${this.term}`;
const routeWithoutTerm = this.$route.fullPath.replace(searchTerm , '');
I want to remove searchTerm from this.$route.fullPath and save it in routeWithoutTerm, but this is obviously the wrong way. It just replaces nothing. How can I achieve this?
EDIT: Lets just say that at execution this.term = 'help' and this.$route.fullPath = 'search/help?term=help' and I want to remove ?term=help
I finally found my problem.
I was having umlauts(ö, ä, ü) in my searchTerm so I had to use encodeURI() on my searchTerm first.
try this to remove search param:
const url = 'https://example.com/posts?page=5&sort=desc';
const urlObj = new URL(url);
urlObj.search = '';
const result = urlObj.toString();
console.log(result); // https://example.com/posts
source
Use substring() function to get the part you want and use replace() to replace it with whatever you want
const const1 = "adios";
const const2 = "muchasgracias";
var result = const2.replace(const2.substring(0,5), const1);
console.log(result);
Related
I am trying to extract all image URLs from an HTML string using regex /<img.*?src="(.*?)"[^>]+>/g in a function like this:
function getImages(string) {
const imgRex = /<img.*?src="(.*?)"[^>]+>/g;
const images = [];
let img;
while ((img = imgRex.exec(string))) {
images.push(img[1]);
}
return images;
}
However, the results also contain non-image stuff, e.g.:
[
'https://www.facebook.com/tr?id=900220307025564&ev=PageView&noscript=1',
'https://cyclingmagazine.ca/wp-content/uploads/2020/10/Peloton-Bike_Cam-1200x675.jpg',
'https://cyclingmagazine.ca/wp-content/uploads/2020/10/ontario-creates-logo.png',
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"></div><div id=',
'https://cyclingmagazine.ca/wp-content/uploads/2019/03/cycling-pop-up.jpg'
]
which breaks subsequent execution. I am by no means a regex expert (clearly), would appreciate any help!
Do not use regex for this. Use the DOMParser API and its parseFromString() method.
let str = "<img src='https://www.example.com'>";
let DOMParsing = new DOMParser()
let parsed = DOMParsing.parseFromString(str, "text/html")
// Now you can use querySelector to target the wanted element
// or querySelectorAll and a loop for multiple elements
let imgURL = parsed.querySelector("img").src
console.log(imgURL)
Hi guys I am trying to take token from url.
I am trying this code
const userURL = document.location;
const shared_token = userURL.split('/')[4].split('?')[0];
alert(shared_token)
my url is something like this:
http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo
But it's show error: userURL.split is not a function. Please help me to correct my code.
Use location.pathname - that can be document.location or window.location - either will work for you: Location object
location.pathname.split("/").pop()
returns
%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK
Using your code:
const userURL = document.location;
const shared_token = userURL.pathname.split('/').pop(); // take the last part of the path
alert(shared_token)
NOTE In the example I use new URL() to make a URL from the URL you provided. You just need document.location
// const shared_token= location.pathname.split("/").pop() in your real code
const shared_token= new URL("http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo")
.pathname
.split("/")
.pop()
console.log(shared_token)
To get parameters AFTER the ? use
// const url = location
const url = new URL("http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo")
const usp = new URLSearchParams(url.search)
const fbclid = usp.get("fbclid")
console.log(fbclid)
this is wrong. document.location returns location object. you are try to split location object. so instead of that try to use const url = document.URL.
ref : Document.URL
const userURL = document.URL;
const shared_token = userURL.split('/')[4].split('?')[0];
alert(shared_token)
You get a Location object back from document.location which already splits up the url for you in handy ways. See the docs for details, but it looks like userURL.search would give you what's after the question mark. So your code could simply to:
// if you want the first value after the '?' you can do this:
const search = document.location.search;
const firstSearch = search ? search.substring(1).split("&")[0] : "";
// if you want the value immediately before the '?' you can do this:
const segments = document.location.pathname.split("/");
const lastSegment = segments[segments.length-1];
You can always use the original userURL.href but see the various parts of Location that are already prepared for you (like host, port, pathname and search).
I would like "category/[categoryName]/[amount]" to become "category/movies/all" (replace "[variable-name]" with the value of the variable with the same name). I have this so far but I'm missing something:
let categoryName = "movies"; // example variable, set somewhere else
let amount = "all"; // example variable, set somewhere else
...
let searchUrl = "category/[categoryName]/[amount]"; // Set dynamically, could be any params
let regex = /\[(.+?)\]/ug;
searchUrl = searchUrl.replace(regex, window['$1']);
but the value of searchUrl just becomes "category/undefined/undefined".
Is what I'm trying to do even possible? Was that asked before and my question title is just malformed? I know how to do this with 2 regexes, first getting the variable names then looping in them and substituting. However I would like to do it with one "replace" only. Is that possible or I have to use 2 regexes?
If I understand correctly for this to work as dynamically as you state you will have to do the following
// example variable, you need to use var so its
// available on the window otherwise this will not work
var categoryName = "movies";
...
let searchUrl = "category/[categoryName]/all";
let regex = /\[(.+?)\]/ug;
let variableName = searchUrl.match(regex)[0];
searchUrl = searchUrl.replace(regex, window['variableName']);
Your dynamic variable will have to be stored globally for this work!
You're so close! What you have now tries to replace [categoryName] with the global variable $1, which doesn't exist. What you want is to use searchUrl.replace(regex, categoryName), assuming categoryName is dynamically set with the correct category.
It seems that with .replace you can enter multiple 'replacers', so you could say str.replace(regex, replacer1, replacer2, replacer3...). Alternatively, you can pass a function to replace a matched value each time one is found.
I just modified your code to:
let categoryName = "movies"; // example variable, set somewhere else
let amount = "all"; // example variable, set somewhere else
// previous answer suggestion
// let replacers = [categoryName, amount];
let searchUrl = "category/[categoryName]/[amount]"; // Set dynamically, could be any params
let regex = /\[(.+?)\]/gu;
let replacers = searchUrl.match(regex).map( m => m.replace(/\[|\]/g,''));
searchUrl = searchUrl.replace(regex, () => { let val = eval(replacers.shift()); return val; });
output => "category/movies/all"
Since your regex is global, it continues to find matches but since there is only 1 replacer in your original code, it replaces the match with that replacer.
i.e. categories/undefined/undefined (using searchUrl.replace(regex, window['$1']);)
You may want to put your replacers into an array. Then with each match, use a function to replace the match with the value stored in the array, as shown in my example above.
Note: This example works for 2 matches only.
Hope this helps.
MDN - Specifying a function as a parameter
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
So I have a URL which is mentioned in the following example; I want to change the value of pageToken to "baz"; but my following attempt is replacing pageToken as well; what is the right way to just change the value of pageToken?
var url = "https://www.googleapis.com/youtube/v3/search?&pageToken=CDIQAQ&foo=bar"
var res = url.replace(/pageToken=\w*/g, "baz");
console.log(res);
//res is now: https://www.googleapis.com/youtube/v3/search?&baz&foo=bar, but my desired output is https://www.googleapis.com/youtube/v3/search?&pageToken=baz&foo=bar
Thanks
The easy way is to include "pageToken=" in the new text:
var res = url.replace(/pageToken=\w*/g, "pageToken=baz");
This will work also:
var res = url.replace(/(pageToken=)\w*/g, "$1baz");