My app is going to work in multiple env, in which i need to get the common value (base url for my app) to work across..
from my window location how to i get certain part from the start..
example :
http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html
how can i get only:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
my try :
var base = \w([yx]/)
the base only select yx/ how to get the value in front of this?
this part..
thanks in advance..
If 'someother' is known to be the root of your site, then replace
\w([yx]/)
with
(.*\/)someother\/
(note that the / characters are escaped here) which gives a first match of:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
However, a regular expression may not be the best way of doing this; see if there's any way you can pass the base URL in by another manner, for example from the code running behind the page.
If you don't mind disregarding the trailing slash, you can do it without a regex:
var url = 'http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html';
url.split('/', 4).join('/');
//-> "http://xxxxx.yyyy.xxxxx.com:14567/yx"
If you want the trailing slash, it's easy to append with + '/'.
Please try following regexp:
http\:\/\/[\w\.]+\:\d+\/\w+\/
This one should do pretty well
http:\/\/[\w\.]+\:\d+\/\w+\/
Perhaps something like this?
Javascript
function myBase(url, baseString) {
if (url && baseString) {
var array = url.split(new RegExp("\\b" + baseString + "\\b"));
if (array.length === 2) {
return array[0] + baseString + "/";
}
}
return null;
}
var testUrl = "http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html",
testBase = "yx";
console.log(myBase(testUrl, testBase))
;
Output
http://xxxxx.yyyy.xxxxx.com:14567/yx/
On jsfiddle
Related
I need to check for a specific URL pattern using regex and not sure what would be the approach but I think it should not be too complex for this case and therefore regex would be the preferred solution. I just need to check that the exact strings #, shares and assets are in the appropriate slots, for example:
http://some-domain.com/#/shares/a454-rte3-445f-4543/assets
Everything in the URL can be variable (protocol, domain, port, share id) except the exact strings I'm looking for and the slots (slash positions) at which they appear.
Thanks for your help!
You can use
/^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i
let url = `http://some-domain.com/#/shares/a454-rte3-445f-4543/assets`
let matched = /^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i.test(url)
console.log(matched)
Decided to avoid regex and do it this way instead.
const urlParts = window.location.href.split('/');
if (urlParts[3] === '#' && urlParts[4] === 'shares' && urlParts[6] === 'assets') {
// code goes here...
}
Let me explain what I mean:
I want to redirect from https://example.net/category/83745/my-first-post to https://myredirect.net/my-first-post but without considering /category/numbers/
For the moment I work with this:
if(window.location.pathname == '/category/83745/my-first-post')
{
window.location.href="https://myredirect.net/my-first-post";
}
And it is working fine but as I described I need to remove /category/numbers/ because they could be different and only consider this part /my-first-post for the redirection.
Thanks in advance.
if you want to just ignore the first 2 parts dynamically and only care about the last part of the URL then just do the following:
var stringContains = function (str, partial){
return (str.indexOf(partial) > -1);
};
var url = '/category/83745/my-first-post';
if(stringContains(url, "/category")){
var parts = a.split("/");
window.location.href = parts[parts.length-1];
}
You can use String's methods lastIndexOf and slice:
var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);
Use Regex. Something like
if(window.location.pathname.match(/\/category\/\d+\/my\-first\-post$/)
{
window.location.href="https://myredirect.net/my-first-post";
}
You can run a regular expression match on the pathname
if(window.location.pathname.match(/my-first-post$/)) {
window.location.href='/my-first-post';
}
More on regexes: https://www.regular-expressions.info/
Another good tool for building and testing regexes: https://regex101.com/
Edit:
To give an example of how to regex according to the more fleshed out specs from Chris G
let pathmatch = window.location.pathname.match(/([^\/]+)$/g);
window.location.href = '/' + pathmatch[0];
Thus, regex can be utilized to grab any pattern and use it later.
IF there is a need to make sure the pathname contains category and/or numbers, it is easily added in to the pattern. This one simply disregards anything before the last forward slash (/)
So let's say the URL I have is
"mywebsite.com/file/100/"
What I want is for it to be updated to
"mywebsite.com/file/101/"
"mywebsite.com/file/102/"
(and so on...)
when the keyword cannot be found.
init();
function init()
{
searchWord("key word");
}
function searchWord(word)
{
var pageResults = document.body.innerHTML.match(word);
if(pageResults)
{
alert("word found");
} else {
}
}
Right now my script searches for a key term, and what I need is for the page to be updated by a value of 1 (100 to 101 to 102 etc) when the keyword cannot be found.
I am a noob a Javascript, none of this code is mine. I just need help developing it. I have searched around for a while, but I can't find much.
Thanks.
Not sure if this gets points for elegance.
Split the url into segments
Dispose of empty segment caused by trailing "/" if present.
If the last segment is numeric, replace it with its numeric value + 1.
Join the segments back into a string.
(If you want the trailing slash you can re-add it.)
Code
var url = "mywebsite.com/file/100/"
var segments = url.split("/");
while(segments[segments.length-1]==""){
segments.pop();
}
var lastSegment = segments[segments.length-1];
if(!isNaN(lastSegment)){
segments[segments.length-1] = (parseInt(lastSegment)+1).toString();
}
updatedUrl = segments.join("/");
One liner just for fun.
var url = window.location.hostname + window.location.pathname.split('/').map(function(sgmt){return (sgmt != '' && !isNaN(sgmt)) ? parseInt(sgmt)+1 : sgmt}).join('/');
You may want to omit the window.location.hostname to use relative url paths instead. The next piece first splits the url at the / and then uses the .map() method on the new array. The function that gets passed looks for non-blank and numerical sections of the url. If it finds it, it adds 1. When finished, it makes the array a string again (with the new number in the url) using the .join() method.
I have following url's and all these url are considered root of the website, how can I use javascript location.pathname using regex to determine pattern below, as you'll notice the word "site" is repeating in this pattern..
http://www.somehost.tv/sitedev/
http://www.somehost.tv/sitetest/
http://www.somehost.tv/site/
http://www.somehost.tv/sitedev/index.html
http://www.somehost.tv/sitetest/index.html
http://www.somehost.tv/site/index.html
I am attempting to display jQuery dialog only and only if the user is at the root of the website.
Simply use the DOM to parse this. No need to invoke a regex parser.
var url = 'http://www.somesite.tv/foobar/host/site';
urlLocation = document.createElement('a');
urlLocation.href = url;
alert(urlLocation.hostname); // alerts 'www.somesite.tv'
A complete pattern, including protocol and domain, could be like this:
/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/
but, if you're matching against location.pathname just try
/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)
If you do not explicitly need a Regular Expression for this
You also could do for example
Fill an array with your urls
Loop over a decreasing substring of
the shortest element.
Comparing it against
the longest element.
Until they match.
var urls = ["http://www.somehost.tv/sitedev/",
"http://www.somehost.tv/sitetest/",
"http://www.somehost.tv/site/",
"http://www.somehost.tv/sitedev/index.html",
"http://www.somehost.tv/sitetest/index.html",
"http://www.somehost.tv/site/index.html"]
function getRepeatedSub(arr) {
var srt = arr.concat().sort();
var a = srt[0];
var b = srt.pop();
var s = a.length;
while (!~b.indexOf(a.substr(0, s))) {
s--
};
return a.substr(0, s);
}
console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site
Heres an example on JSBin
In mongodb the equivalent to sql "like" operator is
db.users.find({"shows": /m/})
Using nodejs/javascript I want to dynamically change letter, based on url paramater.
I have tried
letter = req.params.letter;
db.users.find({"shows": '/' + letter + '/'})
This doesn't work, I guess because the slashes are now strings are interpreted differently.
One way to do it, according to the documentation page:
db.users.find( { shows : { $regex : letter } } );
+1 for mindandmedia on the syntax. However, please remember, that if you want the query to use an index efficiently, you have to use prefix queries (also called rooted regexps) like /^prefix/
Your query is likely to be horribly slow otherwise - see the note in the docs here:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
You can try this:
let filter = "Dynamic";
let str = /.*Raj.*/;
console.log(str);
console.log(typeof(str));
let stra = eval(`/.*${filter}+.*/`);
console.log(stra);
console.log(typeof(stra));