I can change the last part (in the URL: child) of the URL, but if the URL's parameters exist, these parameters are deleted by this change (?para=1¶=2).
Is there a way to not delete the parameters?
Sample:
https://example.com/sub/child?para=1¶=2
JS:
const str = window.location.href;
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path + "/new_child";
window.history.pushState("object or string", "Title", new_path);
window.history.replaceState("object or string", "Title", new_path);
Before replacing the last part you can save the parameters like this
var str = "https://example.com/sub/child?para=1¶=2";
var params = str.split('?')[1]
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path + "/new_child?"+params;
console.log(new_path)
Alternatively you can create a function to do this using regex
var str = "https://example.com/sub/child?para=1¶=2";
const new_path = replaceUrlPart(str, "child", "new_child")
console.log(new_path)
function replaceUrlPart(url, partToRemove, partToAdd){
return url.replace(partToRemove,partToAdd);
}
Related
Let's say that this is my URL/Link that i have written in an input
https://www.instagram.com/p/CBt-W4jHZjH/
How can I get the "CBt-W4jHZjH" part?
var link = ?????
var a = link.val().trim();
var regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/);
var validation = regex.test(a);
https://developer.mozilla.org/en-US/docs/Web/API/URL
const getLastPath = (url) => {
url = new URL(url);
const pathname = url.pathname;
const paths = pathname.split("/");
return paths.pop() || paths.pop();
}
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH/")); // "CBt-W4jHZjH"
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH")); // "CBt-W4jHZjH"
Many ways to do it. One way is to look for / any character but / ending with / end of line.
var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.match(/\/([^\/]+)\/?$/)[1])
Could be done with split. The filter removes the empty string caused by the trailing /.
var url = 'https://www.instagram.com/p/CBt-W4jHZjH/'
var x = new URL(url);
console.log(x.pathname.split('/').filter(x=>x).pop());
How can skip match with Regex i wanna to get ss and skip =
Code:
var patt = new RegExp("=ss","g");
var url = "https://mass.lass.com/?t=ss";
var x = url.match(patt);
console.log(x);
//result
=ss
i only need SS
Use a positive lookbehind. Instead of
new RegExp("=ss","g")
you can use
new RegExp("(?<==)ss", "g")
Try this function (more generic), it takes params and url as a parameters
const url = "https://mass.lass.com/?t=ss";
const getQueryParams = ( url, params ) => {
let reg = new RegExp( '[?&]' + params + '=([^&#]*)', 'i' );
let queryString = reg.exec(url);
return queryString ? queryString[1] : null;
};
console.log(getQueryParams(url, "t"))
I have a string like below
var indicator = -65(www.anyweb.com)
the number -65 can be any number too. How can I take out only the web url separately in javascript?
You need to extract the string after '(' and before ')'
var str = "-65(www.anyweb.com)";
str = str.substring(str.lastIndexOf("(")+1,str.lastIndexOf(")"));
You can use this example for string operations
var data = "-65(www.anyweb.com)";
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')')); console.log("URL :: ",url);
var domain = /\((.*?)\)/.exec("-65(www.anyweb.com)")[1];
console.log(domain);
The regex above will create a group with anything that's inside parenthesis.
You can use some simple string operations:
var str = "-65(www.anyweb.com)";
var url = "N/A";
// Find indices of open and close parentheses
var open = str.indexOf("(");
var close = str.lastIndexOf(")");
// If they were found then extract the URL from the string
if (open !== -1 && close !== -1) {
url = str.substring(open + 1, close);
}
console.log(url);
If you are more inclined to use regular expressions then this should do it:
var str = "-65(www.anyweb.com)";
var regex = /\((.*?)\)/; // Capture URL inside parentheses
var result = regex.exec(str); // Execute the regex against the string
var url = "N/A";
// If the URL was matched then assign it to the variable
if (result[1] !== undefined) {
url = result[1];
}
console.log(url);
You can also simply replace the stuff that you do not want:
var str = "-65(www.anyweb.com)";
str = str.replace(/^.*\(/, ""); // Remove everything before URL
str = str.replace(/\).*$/, ""); // Remove everything after URL
console.log(str);
Example 1 :
var data = "-65(www.anyweb.com)";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 2 :
var data = "-65";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 3 :
var data = "-65(www.anyweb.com)6764872";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
I have an URL like this
localhost:8080/myroot/dir1/dir2/myTestpage.do
I need to get the string upto the root like this
var myURL = "localhost:8080/myroot/";
I tried the slicing but did not work:
var str = "localhost:8080/myroot/dir1/dir2/myTestpage.do";
var myURL = str.split("/").slice(-3, -2).toString();
How can I get the string upto "localhost:8080/myroot/" ?
A fiddle is here
How can I get that string from the url pattern?
This should work:
var str = "localhost:8080/myroot/dir1/dir2/myTestpage.do";
var myURL = str.split('/').slice(0,2).join('/') + '/';
Or more simply:
var myURL = str.split('/', 2).join('/') + '/';
Alternatively, you can use a regular expression like this:
var myURL = str.match(/[^\/]*\/[^\/]*\//)[0];
Or this:
var myURL = str.match(/.*?\/.*?\//)[0];
Modifying you var myUrl = line will make it work
var myURL = str.split("/").slice(0, 2).toString().replace(",", "/") + "/";
You can simply do this :
var myURL = str.split("/");
myURL = myURL[0] + '/' + myURL[1];
Fiddle link : http://jsfiddle.net/hnVnm/2/
And just to have a regex solution also:
"localhost:8080/myroot/dir1/dir2/myTestpage.do".match(/^(https?:\/\/)?[^\/]+\/[^\/]+\//)[0];
Fast and dirty:
var str = "localhost:8080/myroot/dir1/dir2/myTestpage.do";
var strSplit = str.split("/");
var myUrl = strSplit[0] + "/" + strSplit[1] + "/";
Try replace or match :
myURL = myURL.match(/^(.*?\/){2}/)[0];
myURL = myURL.replace(/^((.*?\/){2}).*$/, '$1');
// (.*?\/){2} : everything until a slash, 2 times
Adding a substring version of the answer:
var myURL = str.substring(0, str.indexOf('/', str.indexOf('/') + 1) + 1);
The key here is the second parameter of indexOf, which creates an offset to start searching from. The offset is also str.indexOf('/')+1, so it's finding the second forward slash as the end index for substring.
How do I get the last word in a URL that is URL between / and / ?
For example:
http://mywebsite.com/extractMe/test
http://mywebsite.com/extractMe
http://mywebsite.com/settings/extractMe/test
http://mywebsite.com/settings/extractMe
Here I would want to get extractMe from the URL.
If the URL is consistent, why not just use:
// Option 1
var url = "http://mywebsite.com/extractMe/test";
var extractedText = url.split("/")[3];
// Option 2
// If when a trailing slash is present you want to return "test", use this code
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var extractedText = urlAry[urlAry.length - 2];
// Option 3
// If when a trailing slash is present you want to return "extractMe", use this:
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var positionModifier = (url.charAt(url.length-1) == "/") ? 3 : 2;
var extractedText = urlAry[urlAry.length - positionModifier];
Here's a working fiddle: http://jsfiddle.net/JamesHill/Arj9B/
it works with / or without it in the end :)
var url = "http://mywebsite.com/extractMe/test/";
var m = url.match(/\/([^\/]+)[\/]?$/);
console.log(m[1]);
output:
test
This accounts BOTH for URLS like http://mywebsite.com/extractMe/test and http://mywebsite.com/extractMe/
function processUrl(url)
{
var tk = url.split('/');
var n = tk.length;
return tk[n-2];
}
Edited.
Regular Expression way:
var str = "http://example.com/extractMe/test";
var match = str.match(/\/([^\/]+)\/[^\/]+$/);
if (match) {
console.log(match[1]);
}