I have a URL that can be divided in 3 parts and I want the middle one.
The URL is like this
http://www.site.com/place?siteurl=http://www.thisIsWhatIwant.com/bla/bla/&XXX
XXX means that the URL continues and may have a lot of characters including %, parenthesis, other ampersands, equal signs, etc...
I want what is in bold. I other words, to get rid of everything that is before the equal sign on siteurl= (including the equal sign) and also get rid of everything that is after the first ampersand after that, including the ampersand... so, after cleaning the URL it would become just:
http://www.thisIsWhatIwant.com/bla/bla/
how do I do that with Javascript's str.replace()?
thanks in advance
Rather than remove the text you don't want, you can extract the text you do want using String.match():
var s = "http://www.site.com/place?siteurl=http://www.thisIsWhatIwant.com/bla/bla/&XXX";
var middle = s.match(/siteurl\=(.*?)\&/i)[1];
You don't want to use String.replace here, use String.split:
if(window.location.search.indexOf('siteurl') > -1) {
var siteurl = window.location.search.split('siteurl=')[1];
siteurl = siteurl.substring(0, siteurl.indexOf('&'));
//do something with siteurl...
} else {
//siteurl is not in the URL.
}
Related
So I currently pass two variables into the url for use on another page. I get the last variable (ie #12345) with location.hash. Then from the other part of the url (john%20jacob%202) all I need is the '2'. I've got it working but feel there must be a cleaner and succinct way to handle this. The (john%20jacob%202) will change all the time to have different string lengths.
url: http://localhost/index.html?john%20jacob%202?#12345
<script>
var hashUrl = location.hash.replace("?","");
// function here to use this data
var fullUrl = window.location.href;
var urlSplit = fullUrl.split('?');
var justName = urlSplit[1];
var nameSplit = justName.split('%20');
var justNumber = nameSplit[2];
// function here to use this data
</script>
A really quick one-liner could be something like:
let url = 'http://localhost/index.html?john%20jacob%202?#12345';
url.split('?')[1].split('').pop();
// returns '2'
How about something like
decodeURI(window.location.search).replace(/\D/g, '')
Since your window.location.search is URI encoded we start by decoding it. Then replace everything that is not a number with nothing. For your particular URL it will return 2
Edit for clarity:
Your example location http://localhost/index.html?john%20jacob%202?#12345 consists of several parts, but the interesting one here is the part after the ? and before the #.
In Javascript this interesting part, the query string (or search), is available through window.location.search. For your specific location window.location.search will return ?john%20jacob%202?.
The %20 is a URI encoded space. To decode (ie. remove) all the URI encodings I first run the search string through the decodeURI function. Then I replace everything that is not a number in that string with an empty string using a regular expression.
The regular expression /\D/ matches any character that is not a number, and the g is a modifier specifying that I want to match everything (not just stop after the first match), resulting in 2.
If you know you are always after a tag, you could replace everything up until the "#"
url.replace(/^.+#/, '');
Alternatively, this regex will match the last numbers in your URL:
url.match(/(?<=\D)\d+$/);
//(positive look behind for any non-digit) one more digits until the end of the string
I am pulling in a string from another web page. I want to read that string into a variable but only after a certain point. Eg:
#stringexample
var variable;
I want variable to equal stringexample but not contain the # how could I do this?
This is how I am using the variable at the moment.
$("#Outputajax").load("folder/"+ variable +".html");
This is the way that works but isn't a variable.
$("#Outputajax").load("folder/webpage.html");
If you just want to trim of the first character, then you can use substring...
var input = "#stringexample";
input = input.substring(1);
//input = "stringexample"
Here is a working example
var myVariable = stringExample.replace('#','');
Could just use variable.substr(1) to cut off the first character.
If you want to specifically remove the hash from the start (but do nothing if the hash isn't there), try variable.replace(/^#/,"")
I understand you want to get everything in the string AFTER the hashtag. The other solutions will leave anything ahead of the hashtag in as well. And substring does not work if the hashtag is not the first symbol.
variable= "#stringexample".split("#")[1];
This splits the string into an array of strings, with the parameter as the point where to split, without including the parameter itself. There will be an empty string as the first parameter, and everything after the hashtag is the second string.
var slicer = function(somestring){
var parsedString = somestring;
parsedString = parsedString.slice(1);
return parsedString
}
// run from yors function with some string
var someYouVar = slicer("#something")
I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");
I have a string from which I am trying to get a specif value. The value is buried in the middle of the string. For example, the string looks like this:
Content1Save
The value I want to extract is "1";
Currently, I use the built-in substring function to get to remove the left part of the string, like this:
MyString = "Content1Save";
Position = MyString;
Position = Position.substring(7);
alert(Position); // alerts "1Save"
I need to get rid of the "Save" part and be left with the 1;
How do I do that?
+++++++++++++++++++++++++++++++++++++++++
ANSWER
Position = Position.substr(7, 1);
QUESTION
What's the difference between these two?
Position = Position.substr(7, 1);
Position = Position.substring(7, 1);
You can use the substr[MDN] method. The following example gets the 1 character long substring starting at index 7.
Position = Position.substr(7, 1);
Or, you can use a regex.
Position = /\d+/.exec(Position)[0];
I would suggest looking into regex, and groups.
Regex is built essentially exactly for this purpose and is built in to javascript.
Regex for something like Content1Save would look like this:
rg = /^[A-Za-z]*([0-9]+)[A-Za-z]*$/
Then you can extract the group using:
match = rg.exec('Content1Save');
alert(match[1]);
More on regex can be found here: http://en.wikipedia.org/wiki/Regular_expression
It highly depends on the rules you have for that middle part. If it's just a character, you can use Position = Position.substring(0, 1). If you're trying to get the number, as long as you have removed the letters before it, you can use parseInt.
alert(parseInt("123abc")); //123
alert(parseInt("foo123bar")); //NaN
If you're actually trying to search, you'll more often than not need to use something called Regular Expressions. They're the best search syntax JavaScript avails.
var matches = Position.match(/\d+/)
alert(matches[0])
Otherwise you can use a series of substr's, but that implies you know what is in the string to begin with:
MyString.substr(MyString.indexOf(1), 1);
But that is a tad annoying.
I need to get the URL of an element's background image with jQuery:
var foo = $('#id').css('background-image');
This results in something like url("http://www.example.com/image.gif"). How can I get just the "http://www.example.com/image.gif" part from that? typeof foo says it's a string, but the url() part makes me think that JavaScript and/or jQuery has a special URL type and that I should be able to get the location with foo.toString(). That doesn't work though.
Note that different browser implementations may return the string in a different format. For instance, one browser may return double-quotes while another browser may return the value without quotes. This makes it awkward to parse, especially when you consider that quotes are valid as URL characters.
I would say the best approach is a good old check and slice():
var imageUrlString = $('#id').css('background-image'),
quote = imageUrlString.charAt(4),
result;
if (quote == "'" || quote == '"')
result = imageUrlString.slice(5, -2);
else
result = imageUrlString.slice(4, -1);
Assuming the browser returns a valid string, this wouldn't fail. Even if an empty string were returned (ie, there is no background image), the result is an empty string.
You might want to consider regular expressions in this case:
var urlStr = 'url("http://www.foo.com/")';
var url = urlStr.replace(/^url\(['"]?([^'"]*)['"]?\);?$/, '$1');
This particular regex allows you to use formats like url(http://foo.bar/) or url("http://foo.bar/"), with single quotes instead of double quotes, or possibly with a semicolon at the end.
You could split the string at each " and get the second element:
var foo = $('#id').css('background-image').split('"')[1];
Note: This doesn't work if your URL contains quotation marks.
If it's always the same, I'd just take the substring of the URL without the prefix.
For instance, if it's always:
url("<URL>")
url("<otherURL>")
It's always the 5th index of the string to the len - 2
Not the best by all means, but probably faster than a Regex if you're not worried about other string formats.
There is no special URL type - it's a string representing a CSS url value. You can get the URL back out with a regex:
var foo = ${'#id').css('background-image');
var url = foo.match(/url\(['"](.*)['"]\)/)[1];
(that regex isn't foolproof, but it should work against whatever jQuery returns)