I need to remove the last part of the url from a span..
I have
<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>
And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/.
But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.
Any Help!!??
as simple as this:
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
Here is a slightly simpler way:
url = url.slice(0, url.lastIndexOf('/'));
$('span').attr('st_url', function(i, url) {
var str = url.substr(url.lastIndexOf('/') + 1) + '$';
return url.replace( new RegExp(str), '' );
});
DEMO
Use this.
$('span').attr('st_url', function(i, url) {
var to = url.lastIndexOf('/') +1;
x = url.substring(0,to);
alert(x);
})
You can see Demo
You could use a regular expression to parse the 'last piece of the url':
var url="http://localhost:8888/careers/php-web-developer";
var baseurl=url.replace(new RegExp("(.*/)[^/]+$"),"$1");
The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".
The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.
RegexBuddy has a great deal of information on all this.
You can see it work here: http://jsfiddle.net/xKxLR/
var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));
First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .
Related
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.
I'm looking to remove a parameter from a URL with a click event. The issue is that the parameter can either have an & before it or not. So the form is either search=MYSEARCHTERM or &search=MYSEARCHTERM.
I have the following which appears to work fine for one or other but not both. I was thinking that I could have an if / else statement one of which contains something like this. (Excuse the crappy regex but I've never written it before)
var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);
$('.searchKeyword').click(function() {
$(this).remove();
var searchKeywordRegx = new RegExp('search=' + searchKeyword);
console.log(searchKeywordRegx);
document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});
Am I way off base here?
Use ? to make something optional in a regexp:
var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
Seems you can do this without regular expressions. If you simply remove that portion of the document location's "search":
document.location.search = document.location.search
.replace('search=' + encodeURI(searchKeyword), '');
Here is my code:
var url="https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE";
In this string i need only
url="https://muijal-ip-dev-ed.my.salesforce.com/"
i need string upto "com/" rest of the string should be removed.
In modern browsers you can use URL()
var url=new URL("https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE");
console.log(url.origin)
For unsupported browsers use regex
use javascript split
url = url.split(".com");
url = url[0] + ".com";
That should leave you with the wanted string if the Url is well formed.
You can use locate then substr like this:
var url = url.substr(0, url.locate(".com"));
locate returns you the index of the string searched for and then substr will cut from the beginning until that index~
Substring function should handle that nicely:
function clipUrl(str, to, include) {
if (include === void 0) {
include = false;
}
return str.substr(0, str.indexOf(to) + (include ? to.length : 0));
}
console.log(clipUrl("https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE", ".com", true));
If the URL API (as suggested by another answer) isn't available you can reliably use properties of the HTMLAnchorElement interface as a workaround if you want to avoid using regular expressions.
var a = document.createElement('a');
a.href = 'https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE';
console.log(a.protocol + '//' + a.hostname);
I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/
I'm trying to extract the current file name in Javascript without any parameters.
$(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/);
var current_path = RegExp.$1;
if ((current_path == 'index.html') || ...) {
// something here
}
But it doesn't work at all when you access like http://example.com/index.html?lang=ja. Sure before the file name will be changed at random.
Any idea?
If you're looking for the last item in the path, try this:
var current_path = window.location.pathname.split('/').pop();
This:
window.location.pathname
will give you something like:
"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"
Then the .split() will split the string into an Array, and .pop() will give you the last item in the Array.
function filename(path){
path = path.substring(path.lastIndexOf("/")+ 1);
return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}
console.log(filename('http://example.com/index.html?lang=ja'));
// returned value: 'index.html'
The filename of a URL is everything following the last "/" up to one of the following: 1.) a "?" (beginning of URL query), or 2.) a "#" (beginning of URL fragment), or 3.) the end of the string (if there is no query or fragment).
This tested regex does the trick:
.match(/[^\/?#]+(?=$|[?#])/);
There is a URL.js library that makes it very easy to work with URLs. I recommend it!
Example
var uri = new URI('http://example.org/foo/hello.html?foo=bar');
uri.filename(); // => 'hello.html'
your regex isn't correct. Instead try to be more specific:
.match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
says:
find any number of alphanumeric or hypens[a-zA-Z\-\_0-9]+ before a fullstop that has between 2 and 4 alphabetic characters [a-zA-Z]{2,4} that combefore either the end (\$) or a question mark (\?)
tested on:
("http://www.example.com/index.html?lang=ja").match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
var current_path = RegExp.$1;
alert(current_path);
try this:
window.location.pathname.substring(1)
You can do something more simple:
var url = "http://google.com/img.png?arg=value#div5"
var filename = url.split('/').pop().split('#')[0].split('?')[0];
Result:
filename => "img.png"