Replace ID in a URL between two markers - javascript

I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?

You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036

/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;

Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";

Related

Javascript : Get value of first and second slash

How do i get first and second slash of a URL in javascript?
URL : http://localhost:8089/submodule/module/home.html
Now i want the value /submodule/module
Below is the code i have been trying
window.location.pathname.substring(0, window.location.pathname.indexOf("/",2))
This got me only /submodule
window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/",window.location.pathname.lastIndexOf("/")-1))
Also this didnt work. Can anyone please guide where i am going wrong.
This should work, it take everything exept the last element of pathname:
let result = window.location.pathname.split('/').slice(0,-1).join('/') + '/'
Only the 1st and 2de item:
let result = window.location.pathname.split('/').slice(0,2).join('/') + '/'
Handle path without file :
// ex: /foo/bar/path.html > foo/bar/
// ex: /foo/bar/ > foo/bar/
let result = (window.location.pathname[window.location.pathname.length -1] !== '/') ? window.location.pathname.split('/').slice(0,-1).join('/') + '/' : window.location.pathname
You can use the split() function, for example like this:
var url = 'http://localhost:8089/submodule/module/home.html';
var parts = url.split('/');
console.log('/' + parts[3] + '/' + parts[4]);
The output will be:
/submodule/module
Try this:
var pathParts = window.location.pathname.split('/');
var result = `${pathParts[1]}/${pathParths[2]}`;
Using a regular expression:
var url = 'http://localhost:8089/submodule/module/home.html'; //or window.location.pathname
var re = /\/\/.+(\/.+\/.+)\/.+/
re.exec(url)[1];
This expression basically says the url is in the format
//[anything](/submodule/module)/[anything]
and to get everything in parentheses.
Functional style
/\/[^/]*\/[^/]*/.exec(window.location.pathname)[0]
You could use a regular expression:
var url = ...
var part = url.match(/https?:\/\/.*?(\/.*?\/.*?)\/.*/)[1]
Explanation:
http Match the group 'http'
s? Match 1 or 0 's'
: Match a semicolon
\/\/ Match '//'
.*? Match anything (non-greedy)
( Start capturing block (Everything captured will be an array element)
\/*?\/.*? Something that looks like /.../...
) End capturing block
\/.* Something that looks like /...
The output of the match method will be an array with 2 elements. The first one is the whole matched string, and the second is the captured group.

Javascript URL depth (level)

Is it possible to get url depth (level) with Javascript?
If I have this url:
www.website.com/site/product/category/item -> depth=4
www.website.com/site/product/category -> depth=3
I would use a regex to determine how many matches there are for a slash followed by one or more characters.
var url = "www.website.com/site/product/category/item";
url.match(/\/.+?/g).length; // returns 4
Edit: Added a few checks against query strings and double slashes. (credit to user Lix for sparking the idea)
var url = "www.website.com/site/product/category/item?url=/query/string/path";
url.split(/[?#]/).shift().match(/\/[^/]+?/g).length;
simply split it by "/" and check the length of returning array
var url = "www.website.com/site/product/category/item";
alert("depth is " + (url.split("/").length - 1));
url = "www.website.com/site/product/category"
alert("depth is " + (url.split("/").length - 1));

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

regular expression to replace links

I have following code to create html links in a plain text. This works fine but the link should not contain .png or .jpg
Any suggestions in adapting the regexp?
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/gi;
return function(text, target) {
var replace = text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>');
return replace
};
You can add anchors and a look-ahead with alternatives to add the restriction:
var urlPattern = /^(?!.*(?:png|jpg)$)(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?$/gi;
function repl (text, target) {
var replace = text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>');
return replace;
};
alert(repl("http://some.site.com/new/1.gif", "_blank"));
alert(repl("http://some.site.com/new/1.png", "_blank"));
The crucial part here is ^(?!.*(?:png|jpg)$): it makes the check start at the beginning of a string, and makes sure there is no png nor jpg at the end.
If you pass longer strings with URLs inside, you can use the following regex that assumes you have no spaces in your URLs:
var urlPattern = /(?!\S*(?:png|jpg)(?:$|\s))(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/gi;

how to regex the string between two tokens and return string without the tokens?

Fighting with regex....
I'm using this to find pieces of HTML-string between certain elements:
for (i = 0; i < 2; i += 1) {
target = block[i]; // like BODY or HEAD
regex = RegExp('<' + target + '>(.)+</' + target + '>');
// in case string passed includes breaks/spaces
data = data.replace(/(\r\n|\n|\r)/gm,"").replace(/\s+/g," ")
.match(regex);
entry = data[0].replace(/<!-- [\s\S]*? -->/g, '');
console.log(entry);
}
While this works fine, it returns something like this:
<head>....everthing I want ....</head>
Question:
How do I need to modifiy the regex, so that I can still specifiy the element whose content I need, but which returns only the content and not content & tokens (like <head></head>).
Thanks!
Use the first matching group instead of the whole match.
regex = RegExp('<' + target + '>(.+)</' + target + '>');
and then...
entry = data[1].replace(/<!-- [\s\S]*? -->/g, '');

Categories

Resources