JS / Node.js string().replace() help also help editing URL - javascript

I am trying to edit a string in Node.js. I am developing a web proxy, and I need to rewrite some stuff.
What I need to rewrite is when there is two querystrings in a URL.
I just need the first one to stay but the rest to be modified to "&".
This is what I got.
.replace(new RegExp(/src="(.*?)?(.*?)?&_get=/gi),'src="$1' + '$2' + '&_get=')
But it's not replacing the querystring but the replace is working.
I also need this in string.replace() specifically. If this is not possible, I would like to know how I can get a URL to redirect to a link that replaces the querystring except the first one.

Based on your input output example in the comments, it seems like there's lots of ways you could do this.
One way would be to find the index of the last "?" and use the substring method to "replace" it.
let str = "balalala?query?_get=https://example.org"
let ind = str.lastIndexOf("?")
let newStr = str.substring(0,ind) + "&" + str.substring(ind+1)

If balalala? is always going to be constant, you can separate that out.
var source = 'balalala?'
var str = 'balalala?query?_get=https://example.org'
var rest = str.replace(source, '');
console.log(`${source}${rest.split('?').join('&')}`);

Related

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

Get base url from string with Regex and Javascript

I'm trying to get the base url from a string (So no window.location).
It needs to remove the trailing slash
It needs to be regex (No New URL)
It need to work with query parameters and anchor links
In other words all the following should return https://apple.com or https://www.apple.com for the last one.
https://apple.com?query=true&slash=false
https://apple.com#anchor=true&slash=false
http://www.apple.com/#anchor=true&slash=true&whatever=foo
These are just examples, urls can have different subdomains like https://shop.apple.co.uk/?query=foo should return https://shop.apple.co.uk - It could be any url like: https://foo.bar
The closer I got is with:
const baseUrl = url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1').replace(/\/$/, ""); // Base Path & Trailing slash
But this doesn't work with anchor links and queries which start right after the url without the / before
Any idea how I can get it to work on all cases?
You could add # and ? to your negated character class. You don't need .* because that will match until the end of the string.
For your example data, you could match:
^https?:\/\/[^#?\/]+
Regex demo
strings = [
"https://apple.com?query=true&slash=false",
"https://apple.com#anchor=true&slash=false",
"http://www.apple.com/#anchor=true&slash=true&whatever=foo",
"https://foo.bar/?q=true"
];
strings.forEach(s => {
console.log(s.match(/^https?:\/\/[^#?\/]+/)[0]);
})
You could use Web API's built-in URL for this. URL will also provide you with other parsed properties that are easy to get to, like the query string params, the protocol, etc.
Regex is a painful way to do something that the browser makes otherwise very simple.
I know that you asked about using regex, but in the event that you (or someone coming here in the future) really just cares about getting the information out and isn't committed to using regex, maybe this answer will help.
let one = "https://apple.com?query=true&slash=false"
let two = "https://apple.com#anchor=true&slash=false"
let three = "http://www.apple.com/#anchor=true&slash=true&whatever=foo"
let urlOne = new URL(one)
console.log(urlOne.origin)
let urlTwo = new URL(two)
console.log(urlTwo.origin)
let urlThree = new URL(three)
console.log(urlThree.origin)
const baseUrl = url.replace(/(.*:\/\/.*)[\?\/#].*/, '$1');
This will get you everything up to the .com part. You will have to append .com once you pull out the first part of the url.
^http.*?(?=\.com)
Or maybe you could do:
myUrl.Replace(/(#|\?|\/#).*$/, "")
To remove everything after the host name.

Get portion of a string using Javascript

I have a string (from the pathname in the url) and I am trying to pull out part of it, but I'm having trouble.
This is what I have so far:
^(/svc_2/pub/(.*?).php)
The string is:
/svc_2/pub/stats/dashboard.php?ajax=1
How can I get a regex that returns /pub/stats/dashboard only?
If it's always that format (I'm assuming the /svc_2/ is always there) this should do it.
var s = "/svc_2/pub/stats/dashboard.php?ajax=1";
var match = s.match(/\/svc_2(.+)\./)[1];
But not if anything comes before that.
For this, using a regex is too much, but here is:
var string = "/svc_2/pub/stats/dashboard.php?ajax=1";
console.log(string.replace(/.*(\/pub.*)\.php.*$/,"$1"));
But you can do it, without a regex, like this
console.log(string.substr(6,string.indexOf(".php")-6));
In both cases, the console.log will give you /pub/stats/dashboard
This is not very flexible, but should work in this specific case.
var basedir = '/svc_2/', str = '/svc_2/pub/stats/dashboard.php?ajax=1';
str = str.substring(basedir.length, str.indexOf('.'));
alert(str);

How to use href.replace in extjs

how to use href.replace in extjs
This is my sample:
'iconCls': 'icon_' + href.replace(/[^.]+\./, '')
href= http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png
Now i want to get text "release_history.png", How i get it.
Thanks
If you just want the filename, it's probably easier to do:
var href = "http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png";
var iconCls = 'icon_' + href.split('/').pop();
Update
To get the filename without the extension, you can do something similar:
var filename = "release_history.png";
var without_ext = filename.split('.');
// Get rid of the extension
without_ext.pop()
// Join the filename back together, in case
// there were any other periods in the filename
// and to get a string
without_ext = without_ext.join('.')
some regex solutions (regex including / delimiter)
as in your example code match the start of the url that can be dropped
href.replace(/^.*\//, '')
or use a regex to get the last part of the url that you want to keep
/(?<=\/)[^.\/]+\.[^.]+$/
update
or get the icon name without .png (this is using lookbehind and lookahead feature of regex)
(?<=\/)[^.\/]+(?=\.png)
Not all flavors of regex support all lookaround reatures and I think Javascript only supports lookahead. so probably your solution is this:
[^.\/]+(?=\.png)
code examples here:
http://www.myregextester.com/?r=6acb5d23
http://www.myregextester.com/?r=b0a88a0a

Extracting a portion of the a href path using Javascript

I'm needing to extract a portion of an href attribute using javascript.
I've come up with a solution, but I'm not sure it's the best way. Below is my sample code. I've got a variable with the complete href path -- and all I'm interesting in extracting is the "Subcategory-Foobaz" portion.
I can assume it will always be sandwiched between the 2nd "/" and the "?".
I'm terrible with Regex, so I came up with what seems like a hokie solution using 2 "splits".
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/")[2].split("?")[0];
console.log(subcat);
Is this horrible? How would you do it?
Thanks
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/").pop().split("?")[0];
console.log(subcat);
Just a small change; use pop() to get the last element no matter how many /'s you have in your string
re = /\/[^\/]+\/([^?]+)/;
str = '/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about';
matches = str.match(re);
console.log(matches);

Categories

Resources