How can remove page and pageSize from given text? - javascript

"?page=2&pageSize=12&query=hex"
I have the above text I want to remove page and pageSize along with value. After removing the page and pageSize my text should look like given below.
"?query=hex"

You can use URLSearchParams to remove params of the query:
const queryString = "?page=2&pageSize=12&query=hex";
const searchParams = new URLSearchParams(queryString);
searchParams.delete("page");
searchParams.delete("pageSize");
const resultQuery = `?${searchParams.toString()}`;
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

here is my solution
text.replace(/(page=\d+&?)|(pageSize=\d+&?)/g, '')

Here's one way of doing it without any third-party library:
const input = "?page=2&pageSize=12&query=hex"
const parts = input
.replace(/^\?/, "")
.split("&")
.filter(p => !/^(page|pageSize)/.test(p))
const output = "?" + parts.join("&")
console.log(output)

Using regex you can do that as below:
const str = "?page=2&pageSize=12&query=hex";
console.log(str.replace(/page.*&/g, ""));

Here, maybe this will help. Simple to implement and understand.
var str = "?page=2&pageSize=12&query=hex";
var finalStr = '?' + str.substring(str.indexOf('query='))
console.log(finalStr)

Related

How to insert value after specific text in the string

I would like to add value to my URL after the specific text. How I can achieve this?
I found a solution where I can slice and add values but I don't have the index fixed in this URL.
const url = 'www.website.com/api/test1/test2';
const url = 'www.website.test.com/api/test1/test2/test3';
const output1 = 'www.website.com/api/ha/test1/test2';
const output2 = 'www.website.test.com/api/ha/test1/test2/test3';
If you want to add a certain value after a certain string you can simply replace the known value with the new string:
url.replace('/api', '/api/ha')
If you don't have a fixed index, you should use Regex to search the string. Could look like this:
/(www.\D+\/api\/)[\D\d\/]+/gm
This code would put the before and after into a group and you can then do
group1 + yourstring + group2
to add it together.
I prefer working with URL
const url1 = new URL('https://www.website.com/api/test1/test2');
const pn = url1.pathname.split("/")
pn.splice(2,0,'ha')
url1.pathname=pn.join("/");
console.log(url1.href)

Extract id from url string

I want to extract the id 1406570408 from the below url. I was wondering if there is a better way than my current try ?
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('/')
str = str[5].split('?')
console.log(str[0]) // 1406570408
how about using url class ?
let url = new URL("https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013")
url.pathname.split('/')[3] //equals the id
here
url.pathname contains webapp/viewer/1406570408
or use
url.pathname.split('/').pop() to remove the last element as #O.Jones pointed out
const url = "https://www.google.de/webapp/viewer/1406570408?pag…-P-Global_Startpage&lat=52.5517268&lng=13.4123013"
const url2 = "https://www.google.de/webapp/viewer/1406570408"
const url3 = "https://www.google.de/webapp/something/1406570408"
const getId = (url) => {
const match = /(?<=viewer\/)\d*/.exec(url)
return match ? match[0] : null;
}
console.log(getId(url))
console.log(getId(url2))
console.log(getId(url3))
let url = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
const segments = new URL(url).pathname.split('/');
const last = segments.pop() || segments.pop();
console.log(last);
Here is the single line plain javascript methods of Arrays
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('?')[0].split('/').reverse()[0]
console.log(str) // 1406570408
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
console.log(str.match(/\d+/)[0]);
Use an regrex to find an numeric value inside a url string
Best way is to parse the URL with the URL JavaScript API, and then extract the piece of data you need from the pathname property provided to you by the URL.
An example for your usecase:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let url = new URL(str); // create an instance of the URL API
let pathname = url.pathname; // pathname property
let segments = pathname.split('/'); // split pathname by / slash
let last_item = segments.slice(-1)[0] || null; // grab the last item from pathname array
console.log(last_item);
Your output will be: 1406570408.
If your pathname is '/' or no pathname at all, you'll receive a null which you can handle later.
Also, the above code could be shortened into:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let last_item = (new URL(str)).pathname.split('/').slice(-1)[0] || null;
console.log(last_item);

get first url segment with a javascript regex

I have this regexp to extract instagram.com usernames
const matches = value.match(
/^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/
);
console.log(matches[1])
It works fine with www.instagram.com/username but it doesn't work with www.instagram.com/username?ref=google
How can I exact only the username from the url?
Thanks for your help.
alternatively, do not use regex. e.g.
const url = "www.instagram.com/username?ref=google";
const oUrl = new URL("http://" + url);
console.log(oUrl.pathname.substring(1));
or
let url = "instagram.com/username?ref=google";
if (!url.startsWith("http://") || !url.startsWith("https://")) {
url = "http://" + url;
}
const oUrl = new URL(url);
console.log(oUrl.pathname.substring(1));
The $ at the end matches the end of the line, but the end of the username isn't necessarily the end of the line. To permit ? after the username as well, use (?:$|\?) instead of $:
^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?(?:$|\?)
https://regex101.com/r/pbpi74/1
You can also try a non-regex way using .substring. You may find it cleaner than regex.
It works with both URLs.
let username = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("?") > 0? url.lastIndexOf("?") : url.length
);
Check fiddle:
https://jsfiddle.net/whx5otvp/

Slice URL to get the file name in Vue

I have a file url and I need to slice it for showing the file to the users. I have successfully sliced it using substring but what if the string to slice isn't fixed. Like this /media/users/3/sample.docx. I wanted to show sample.docx only so I used substring but what if the numbers before that, increases like the number 3? How can do it the better way?
sliceString(value) {
return value.substring(15)
}
{{sliceString(data.file)}}
Take the last index of /, add 1 to it and use in the substring method :
sliceString(value) {
let lastSlashIndex=value.lastIndexOf('/')
return value.substring(lastSlashIndex+1)
}
Example:
let url = 'sample.com/media/users/3/sample.docx'
let lastIndex= url.lastIndexOf('/');
console.log(url.substring(lastIndex+1))
Try to use value.lastIndexOf()
sliceString(value) {
return value.substring(value.lastIndexOf("/")+1)
}
{{sliceString(data.file)}}
Try using split:
const url = 'sample.com/media/users/3/sample.docx';
url = url.split('/');
len = url.length;
const sample = url[len-1];
console.log(sample) // 'sample.docx'
You can use regex to do it like that
const url = 'sample.com/media/users/3/sample.docx'
console.log(url.match(/[^\/]+$/)[0])
This should shrink the URL to just the filename even if there are query string parameters :
const fileString = 'file:///folder1/folder2/folder3/filename.extension?possibleQueries';
sliceURL = ((url) => {
lastChar = url.length;
if (url.lastIndexOf('?') > -1) {
lastChar = url.lastIndexOf('?');
};
return (url.substring(url.lastIndexOf("/") + 1, lastChar));
})
(fileString); // Expected output: "filename.extension"

How to convert a string with commas to a string with hashtags - ES6

How to convert a string with commas to a string with hashtags. Could anyone please help?
What I tried so far is below. It gives individual elements when used map. How do i make it a single string with # appended before each item in the array.
const tags = 'caramel,vanilla,chocolate';
const splitArray = tags.split(",").map(val=> console.log('#'+val));
You can use .replace() instead with global and extend with # in the beginning.
Extend with template literals, using # in the first character's place:
const tags = 'caramel,vanilla,chocolate';
const result = `#${tags.replace(/,/g, '#')}`;
console.log(result);
Or as Patrick suggested in the comment section with /^|,/g in the RegExp:
const tags = 'caramel,vanilla,chocolate';
const result = tags.replace(/^|,/g, '#');
console.log(result);
You can use .join(''):
const tags = 'caramel,vanilla,chocolate';
const result = tags.split(",").map(val=> "#"+val).join('');
console.log(result);
Using Reduce.
const tags = 'caramel,vanilla,chocolate';
const splitArray = tags.split(",").reduce( (res,val) => (res+'#'+val) ,'');
console.log(splitArray);
I believe that basic replace will make it faster.
Check this:
const tags = 'caramel,vanilla,chocolate';
var hastags = (tags, sp) => {
return typeof tags === "string" && tags.trim() ? "#" + tags.replace(sp || ",", "#") : "";
};
console.log(hastags(tags, ","));

Categories

Resources