Here is the url where I am getting lost. What is the issue?
I am getting the value as:
mydomain.mymaindomain.com/http://mydomain.mymaindomain.com/asppage.asp?paramsgoes---
But sometimes it comes as:
http://mydomain.mymaindomain.com/asppage.asp?paramsgoes---
So I want to make sure that if the mydomain.mymaindomain.com/ comes extra, I want jquery to try to remove it. I am lost as to where I try to do it.
It is not showing http:// but it could be applying or it could not be applying, I'm not sure at this point.
One way would be to check whether the last occurrence of http is at the beginning of the string or somewhere in the middle. There's no need for jQuery, this is vanilla JS:
str = 'http://somedomain';
var pos = str.lastIndexOf('http');
if (0 != pos) {
str = str.substring(pos);
}
This will return http://mydomain.mymaindomain.com/asppage.asp? for:
http://mydomain.mymaindomain.com/asppage.asp?
http://mydomain.mymaindomain.com/http://mydomain.mymaindomain.com/asppage.asp
mydomain.mymaindomain.com/http://mydomain.mymaindomain.com/asppage.asp
Demo
Try before buy
Related
I have an Array with one or more entries. Each one is a string (List of urls in open Tabs via Firefox SDK). I want to check if a specific url is already opened in some of the tabs (nothing special till now).
My problem is, that the url in tab list can have four diffrent fourms. For example:
Url I want to find in the tablist:
https://cmsr-author.de/cf#/content/test/de.html
But the url can also look like this:
https://cmsr-author.de/content/test/de.html
https://cmsr-author.de/test/de.html
https://cmsr-author.de/cf#/test/de.html
Of course the last part of the url (after /test/...) is always something diffrent. If I wasn't able to find one of the four urls in the tablist i want to call some other action.
My Solution till now is to build some if-chain:
if (res !== url1) {
if (res !== url2) {
if ...
But i thought there must be some more elegant way. Maybe via RegEx? I already have a capture to catch the first part (which stays the same https://cmsr-author.ws...) with it four forms. But i dont know how to implent this probably.
var urls = ["https://cmsr-author.de/content/test/de.html","https://cmsr-author.de/test/de.html","https://cmsr-author.de/cf#/test/de.html"]
var filtered = urls.filter(function(url)
{
return url.indexOf("cf#") > -1 && url.endsWith("/test/de.html")
})
var contains = filtered.length > 0
console.log(contains)
If you want to use regex you can do this by using groups for the middle part, which is explained in detail here: http://www.regular-expressions.info/refcapture.html
Practically, your regex would look something like that:
https:\/\/cmsr-author\.de\/(content|...|...)\/de\.html
Where ... must be replaced by the middle parts of the url which differ.
Note that | is "or" used to provide multiple possibilities within the group. The character / and . must be escaped since they have special roles in regex.
I hope that helps!
My English is not good,Do not fully understand what you mean,According to my idea,You should need a regular expression,Only to match the first.If I am wrong,
please # me.
I hope that helps!
var reg = /^https:\/\/cmsr\-author\.de\/cf#\/(?:\w+\/)+test\/de\.html$/gi;
var str1 = "https://cmsr-author.de/cf#/content/test/de.html";
var str2 = "https://cmsr-author.de/content/test/de.html";
var str3 = "https://cmsr-author.de/test/de.html";
var str4 = "https://cmsr-author.de/cf#/test/de.html";
console.log(reg.test(str1));
console.log(reg.test(str2));
console.log(reg.test(str3));
console.log(reg.test(str4));
I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.
Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).
I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.
Is there an equivalent function in JavaScript or jQuery similar to strpos in PHP?
I want to locate a string inside an element on a page. The string I'm looking for is:
td class="SeparateColumn"
I would like something where I can run it like this to find:
if $("anystring")
then do it
I assume you mean check whether a string contains a character, and the position in the string - you'd like to use the indexOf() method of a string in JS. Here are the relevant docs.
Okay, so you'd like to search the whole page! The :contains() selector will do that. See the jQuery docs for :contains.
To search every element in the page, use
var has_string = $('*:contains("search text")');
If you get jQuery elements back, then the search was a success. For example, on this very page
var has_string=$('*:contains("Alex JL")').length
//has_string is 18
var has_string=$('*:contains("horsey rodeo")').length
//has_string if 0. So, you could an `if` on this and it would work as expected.
You don't need jquery for this -- plain old Javascript will do just fine, using the .indexof() method.
However if you really want an exact syntax match for PHP's strpos(), something like this would do it:
function strpos (haystack, needle, offset) {
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}
Note: This function taken from here: http://phpjs.org/functions/strpos:545
JSFiddle