Trying to remove the full url that is being returned to imgurl:
Usually returns something like http://localhost/wordpress/wp-content/uploads/filename.jpg
or http://localhost/wordpress/wp-content/uploads/images/filename.jpg
I'd like to strip off everything except filename.jpg and return it to
ahng_photos_upload_image. Strip off everything to the last forward-slash.
How can I do that with Jquery?
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#ahng_photos_upload_image').val(imgurl);
tb_remove();
}
You don't need jQuery for that, just plain old JavaScript will do :)
alert('http://localhost/wordpress/wp-content/uploads/filename.jpg'.split('/').pop());
In your case:
var filename = imgurl.split('/').pop();
you can use a regular expression in order to achieve this..
var file = imgUrl.replace(/^.*[\\\/]/, '');
Now the file would consist of only the file name ..
If you're pretty confident that the URLs don't have funny stuff like hashes or parameters, a regex like this would do it:
var filename = imgurl.replace(/^.*\/([^/]*)$/, "$1");
Also: don't forget to declare "imgurl" with var, and you should probably use .prop() instead of .attr() if your version of jQuery is 1.6 or newer:
var imgurl = jQuery('img', html).prop('src');
Also jQuery internally turns the two-argument form of the function into this:
var imgurl = jQuery(html).find('img').prop('src');
so you might as well code it that way.
One further option:
var filename = imgurl.substring(imgurl.lastIndexOf('/') + 1);
JS Fiddle demo.
Here you have
var filename = imgurl.split('/').slice(-1);
Good luck!
Try this one:
imgurl.split('/').slice(-1);
Edit: Look at the version of #Andy who uses the pop() method, the latter being faster than slice(-1).
Note that if you don't know if you have forward or backward slashes, you are better off using the RE version of split:
"path".split(/[\/\\]/).slice(-1)
Here is an answer that will work when your file name is like ./file.jpg
var extension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
var baseName = fileName.replace(/^.*\/([^/]*)$/, "$1");
var path = fileName.replace(/(^.*\/)([^/]*)$/, "$1");
Related
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 (/)
I'm taking the following ex URL https://support.dev.mysite.com/batch/ and removing everything, but the environment (eg dev). The below code works fine.
var env = endPoint.replace("https://support.", "\n");
var envClean = env.replace(".mysite.com/batch/", "\n");
I don't like repeating myself. I would like to look for both patterns in the string and remove them all at once. MDN has a good breakdown of replace() here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace but it doesn't mention anything about multiple arguments.
I've tried this:
var env = endPoint.replace("https://support." && ".mysite.com/batch/", "\n");
but it just parses the second arg and disregards the first.
Does anyone have a cleaner way of doing this? I'm assuming I can search for multiple patterns via REGEX, any REGEX masters out there care to help?
Cheers.
You can use regular expressions for this:
var environment = 'https://support.dev.mysite.com/batch/'
.replace(/^https:\/\/support\.|\.mysite\.com\/batch\/$/g, '');
You could chain your method:
var envClean = endPoint.replace("https://support.", "\n").replace(".mysite.com/batch/", "\n");
Or you could use regex:
var envClean = endPoint.replace(/https:\/\/support\.|\.mysite\.com\/batch\//, "\n");
And there is another solution to get dev:
var envClean = endPoint.match(/^https:\/\/support\.([^.]*)\.mysite\.com\/batch\/$/)[1];
For this specific URL pattern, why not make it really simple and use .split():
var url = 'https://support.dev.mysite.com/batch/';
var name = url.split('.')[1];
If I were using a regular expression, I would probably do it this way:
var match = url.match( /support\.(.*)\.mysite.com/ );
var name = match && match[1];
Note that you don't have to worry about the entire URL this way, only enough to do the match.
If you know that the URL will match, you can simplify that to:
var name = url.match( /support\.(.*)\.mysite.com/ )[1];
I'm trying to extract a string from an url. The URL can either be:
http://page.de/s/project.html?id=1
or
http://page.de/s/project.html?id=1/#/s/project.html?id=x
I need to extract the last ?id=-value but I can't get it to go. This is what I have:
url_snip = key.replace("?id=","")
which only works for the first URL.
Question:
Is there a regexp or method to get the last id value no matter whats the URL?
Thanks!
You can extract using split on location.search
var ids = window.location.search.split('&')[0].split('=');
ids[0] //id;
ids[1] //1
Given the two forms you posted:
url_snip = key.substring(key.lastIndexOf('=') + 1);
JS Fiddle demo (admittedly using a function, but it's the same approach).
And an alternative, using split():
var parts = url.split('=');
return parts[parts.length - 1];
JS Fiddle demo.
How can I use jquery on the client side to substring "nameGorge" and remove "name" so it outputs just "Gorge"?
var name = "nameGorge"; //output Gorge
No jQuery needed! Just use the substring method:
var gorge = name.substring(4);
Or if the text you want to remove isn't static:
var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');
Using .split(). (Second version uses .slice() and .join() on the Array.)
var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer
Using .replace().
var result = name.replace('name','');
Using .slice() on a String.
var result = name.slice( 4 );
Standard javascript will do that using the following syntax:
string.substring(from, to)
var name = "nameGorge";
var output = name.substring(4);
Read more here: http://www.w3schools.com/jsref/jsref_substring.asp
That's just plain JavaScript: see substring and substr.
You don't need jquery in order to do that.
var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);
var name = "nameGorge";
name.match(/[A-Z].*/)[0]
Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well.
http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?
How about the following?
<script charset='utf-8' type='text/javascript'>
jQuery(function($) { var a=$; a.noConflict();
//assumming that you are using an input text
// element with the text "nameGorge"
var itext_target = a("input[type='text']:contains('nameGorge')");
//gives the second part of the split which is 'Gorge'
itext_target.html().split("nameGorge")[1];
...
});
</script>
$('img').click(function(){
var add_to_list = $(this);
// database query for element
});
Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or without the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.
Have you tried javascript replace function ?
You should modify your code to something like this:
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('images/', '');
// database query for element
});
use
add_to_list.substring(7);
This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().
add_to_list.split("/").pop();
substring
split
pop
This tutorial explains many of the string manipulation methods seen in the answers here.
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('image/', '');
// database query for element
});
var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];