Extract part of current url to use in javascript function - javascript

hoping someone who knows a bit about javascript maybe able to help me. I need to extract part of the url of my pagepage to use in a javascript function and append to a url. ( it's for a power reviews setup.) the portion i need to extract is the number of the example below ie. www.mydomain.com/my-product-could-be-i950.html -- so would just need the 950 part.. the number part could be 2,3,4 characters. I then need to append this to the url www.mydomain.com/write-a-review.html?pr_page_id=950
could anyone help, it's a bit beyond me this one to be honest..
Many thanks.. Nathan

var num = location.pathname.match(/(\d+)\.html$/);
if( num ) {
var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}

Try this:
<script type="text/javascript">
function changeURL()
{
var szURL = location.pathname;
szURL = "www.mydomain.com/my-product-could-be-i950.html";
var num = szURL.replace(/\D/gi, "");
szURL = "www.mydomain.com/write-a-review.html?pr_page_id=" + num;
//Set URL
}
</script>

you could use regex:
var re = /i([0-9]{2,4})\.html$/;
var m = document.location.match(re);
if (m){
document.location.href = 'http://www.mydomain.com/write-a-review.html?pr_page_id='+m[1];
}

//current page URL
cur = window.location
//regex to match your number
regex = /i[0-9]{2,4}\.html/;
//your number
num = cur.match(regex);
alert(num);
Not tested, Note that the variable num could be an array.

Related

remove a specific area from url using jquery

I have a URL such as http://myurleg.com/ar/Message.html and I want to replace ar with en in it, after clicking on it.
It means that if my url is: http://myurleg.com/ar/Message.html
After click it should become: http://myurleg.com/en/Message.html
I just tried
<script>
$(document).ready(function () {
$('#lng_flip').click(function () {
var url = window.location.href.split('/')[0];
});
});
</script>
Can anyone help?
You can user string replace :
var str = "http://myurleg.com/ar/Message.html";
document.write(str);
var res = str.replace("/ar/", "/fr/");
document.write('<br /> Result : ' + res );
var current = location.pathname.substring(1, 3);
var flipped = current == 'en' ? 'ar' : 'en';
location.pathname = '/' + flipped + location.pathname.substring(3);
Try this
var str = 'http://myurleg.com/ar/Message.html';
var txt = str.replace(/ar/i,"en");
Or in your case
var url = window.location.href;
window.location.href = url.replace(/ar/i,"en");
A general solution, supporting any two-letter language code at the beginning of the path, would be:
location.href = location.href.replace(/(\/\/.*?\/)\w{2}(.*)/, '$1en$2');
Though sometimes it makes more sense to only manipulate location.pathname:
location.pathname = location.pathname.replace(/\/\w{2}(.*)/, '/en$1');
Replace ar in split('/') array with en and join it again using join('/')
var url ='http://myurleg.com/ar/Message.html'.split('/');
url[3]='en';
url=url.join('/');
document.write(url);

Last Segment before the question mark ( ? ) in Javascript

Here is the URL
http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a
I want to grab the last segment of my URL before the ?, ignore what after the ?
Can someone please teach me how to do that ?
I've tried
var href = location.href;
var lastSegment = href.substr(href.lastIndexOf('/') + 1);
console.log(lastSegment);
I got
assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a
I only want assignment
Try this
var pathParts = location.pathname.split('/'),
basename = pathParts[pathParts.length - 1];
Or this super handy one-liner (sometimes I have to remind myself that arrays have methods)
var basename = location.pathname.split('/').pop();
See URLUtils.pathname
var lastSegment = href.substring(href.lastIndexOf('/') + 1, href.lastIndexOf('?'));
You have to also limit your end - and use substring instead of substr.
Here's a fiddle too ;)
http://jsfiddle.net/jf2xrahx/
Try utilizing String.prototype.match()
var url = "http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a";
var res = url.match(/\w+\?/)[0].slice(0, -1);
document.write(res);

Get url from iframe and onclick modify the address

I'm trying to find a way to get a url from an iframe and using javascript modify the link and move to a another page. basicly the address in the iframe is something like "http://www.somthing.com/12/somt/arr_1.htm", using the javascript I want to remove the last five character (leaving this "http://www.somthing.com/12/somt/arr_") and than add the next logical number to it (making the link this "http://www.somthing.com/12/somt/arr__2.htm").
So far I have something like this.
<script language="javascript" type="text/javascript">
function urlGen(f){
var i1 = document.getElementById("iframe_id").contentWindow.location.href;
var i2 = "1.htm";
var i3 = "2.htm";
var newURL = i1 - i2 + i3
f.action = i1 - i2 + i3
return i1 - i2 + i3;
}
</script>
So based on what I understand from what you said it should look something like this?
so it should look something like this? (keep in mind I'm the forest gump of javascript... "I'm not a smart man but I know what java is")
<script language="javascript" type="text/javascript">
function urlGen(f){
var i1 = document.getElementById("iframe_id").contentWindow.location.href = newURL;
newURL = il.slice(0, -5);
var i3 = "2.htm";
f.action = newURL + i3
}
</script>
Try with this regular expression match
var i1 = "http://www.somthing.com/12/somt/arr_41.htm";
s = i1.replace(/\d+\.htm$/, function(attr) {
return attr.replace(/\d+/, function(val) {
return parseInt(val,10) + 1;
});
});
alert(s);
This will change any string that ends in X.htm (where X is a digit) in the same string with X+1 in place of X (adapted from https://stackoverflow.com/a/1742841).
You are grabbing the url correctly however your string manipulation isn't going to work.
You have a special function for trimming the string:
newUrl = i1.slice(0, -5);
This will trim the last 5 characters of the url.
newUrl = newUrl + i3;
This will concat the modified url with the new one.
return newUrl;
now when you do:
document.getElementById("iframe_id").contentWindow.location.href = newUrl;
It will use the new url.
With working example:
This example also incorporates the number addition:
i1.substr(0,i1.lastIndexOf("_")+1);
This bit uses the string function substr. It is used to retrieve part of a string. The first parameter is the start location, while the second marks the end. I use the string function lastIndexOf to find the location of the last used underscore in the url, then add one to make sure it includes the underscore. The code line above will print:
http://stacksnippets.net/arr_
To build the new url, we need to now the number. parseInt helps ur here:
(parseInt(i1.substr(i1.lastIndexOf("_")+1), 10)+1)
I've put the entire part between brackets so it parses it as a sum. The first parameter of parseInt is the string containing the number (1.htm). We select this again by using substr. Now the starting location is the underscore + 1. The last argument is omitted since we can go till the end of the string. parseInt will parse 1.htm to 1. The second argument is used to force the function to use the decimal system. (radix 10). The last part of the sum adds one to the number. The result of this piece of code will be 2.
Appending it all together will give us:
http://stacksnippets.net/arr_2.htm
function urlGen(f) {
var i1 = "http://stacksnippets.net/arr_1.htm"; //cannot grab the url because of same origin policy
//var i1 = document.getElementById("iframe_id").contentWindow.location.href; //
var newURL = i1.substr(0,i1.lastIndexOf("_")+1) + (parseInt(i1.substr(i1.lastIndexOf("_")+1), 10)+1) + ".htm";
f.action = newURL;
return newURL;
}
//NOT PART OF THE SOLUTION:
document.body.onload = function() {
document.body.innerHTML += "Document initial url: http://stacksnippets.net/arr_1.htm";
var url = urlGen(new Object); //dummy object
document.body.innerHTML += "<br />Changed url: " + url;
}

How to get the last two characters of url with jQuery?

I have a url with the following format:
base/list.html?12
and I want to create a variable which will be equal to the digits after the question mark in the url of the page. Something like:
var xxx = anything after the ? ;
Then I need to load dynamic data into that page using this function:
if(document.URL.indexOf(xxx) >= 0){
alert('Data loaded!');
}
How can I achieve this? and are the codes above correct?
Thanks
You can use split to get the characters after ? in the url
var xxx = 'base/list.html?12';
var res = xxx.split('?')[1];
or for current page url
var res = document.location.href.split('?')[1];
res = document.location.href.split('?')[1];
Duplicate of 6644654.
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var search = parseUrl('base/list.html?12').search;
var searchText = search.substr( 1 ); // removes the leading '?'
document.location.search.substr(1) would also work

remove parts of string with javascript

I have somewhat of an odd situation, where I need to fix a bug in a website where, when a string is created (dynamically) it adds 5 spaces before the string and 5 spaces after the string. Obviously, the best thing to do would be to fix the back end code and get rid of those spaces... long story short, I can't and I have to do it with javascript. I'm not quite sure how to do it, but this is what I was thinking
<!--Dynamically generated string including spaces added in backend-->
<span id="balance"> 245.34 </span>
My idea was to do the following with javascript
function removespace()
{
var oldString = document.getElementById('balance');
var newString = (THIS IS WHERE I AM STUCK... I NEED TO REMOVE THE SPACES);
document.getElementByID('balance').innerHTML = newString;
}
Does anyone have any suggestions?
Thanks!
ALSO FORGOT TO MENTION: I can't use any javascript libraries like prototype or jquery.
Edit: I have this so far... but it doesn't seem to be working:
<span id="balance"> $245.00 </span>
<script>
function removespace()
{
var oldString = document.getElementById('balance');
var newString = oldString.trim ();
document.getElementByID('balance').innerHTML = newString;
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
here is the solution I used... I finished it before I saw the other updates... but everyone was very helpful
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var oldString = document.getElementById('balance').innerHTML;
var newString = trim(oldString);
document.getElementById('balance').innerHTML = newString;
Unfortunetly JavaScript does not have a trim() function. But you can roll your own:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
and then do:
var newString = oldString.trim ();
the above function is from this website (first result on google for "javascript trim")
edit (based on your update to your question and comments):
change
var oldString = document.getElementById('balance');
to
var oldString = document.getElementById('balance').innerHTML;
and change
document.getElementByID('balance').innerHTML = newString;
to
document.getElementById('balance').innerHTML = newString; // notice the lower case d
and you have to call the removespace function at some point (but I'm sure you already do that) :)
Writting out of my head here.
var elem = doc.getElementById('balance');
var oldString = elem.innerHTML;
elem.innerHTML=oldString.(/^\s+|\s+$/g,"")
Something like that?
Edit: yep, only my first space is deleted, so I stole the whitespace from the answer number 1 :)
You try something like this
str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
use trim() to remove all white spaces
var newString = oldString.trim();
or use replace to replace white spaces with empty string:
var newString = oldString.replace(" ","");
with jQuery it's simple:
var newStr = jQuery.trim(oldStr);
If balance is meant to be a double you could convert it to a string:
var c = '1234';
d = c * 1;
then back to a string if need be by:
d = c.toString();

Categories

Resources