Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx
What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:
Example (pseudo-code)
if(url contains http://store.mywebsite.com/folder-1)
do this
else if (url contains http://store.mywebsite.com/folder-2)
do something else
etc
In the interest of keeping things very simple...
if(location.pathname.indexOf("folder-1") != -1)
{
//do things for "folder-1"
}
this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.
I would split() the string and check an individual component of the url:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
// split the string into an array of parts
var spl = str.split("/");
// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
// do something
} else if (spl[4] == "folder-2") {
// do something else
}
Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".
Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
// do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
// do something
}
Assuming the base URL is fixed and the folder numbers can be very large then this code should work:
var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
, regex = /^http:..store.mywebsite.com.(folder-\d+)/
, match = url.match(regex);
if (match) {
if (match[1] == 'folder-1') {
// Do this
} else if (match[1] == 'folder-2') {
// Do something else
}
}
Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions
Related
I have this code and it needs to returns true or false based on the string you give it.
This is the only example on which it doesn't work. How can I check if brackets exist in a specific index of the string?
function telephoneCheck(str) {
var newStr = str.replace(/-/g,'').replace(/ /g,'').replace(/\(|\)/g,'');
var valid = true;
var re = /\([^()]*\)/g;
while (str.match(re))
str = str.replace(re, '');
if (str.match(/[()]/)){
valid = false;
}
if(newStr.length === 10 && valid === true && str.indexOf()){
return true;
}else if(newStr.length === 11 && str[0] != "-" && newStr[0] == 1 && valid === true){
return true;
}else{
return false;
}
}
telephoneCheck("(6505552368)");
Based on your code I think you might be looking for something like this:
'(6505552368)'.replace(/^\((\d+)\)$/, '$1');
The ^ and $ in the RegExp will match the start and the end of the string. The \d+ will match one or more numbers. The extra parentheses form a capture group that is then used in the replacement as $1.
You might be better off doing more work using RegExps rather than doing all that replacing but without knowing the exact requirements it's difficult to be more precise. I highly suggest learning more about RegExp syntax.
If you literally just want to know whether 'brackets exist in a specific index' then you can just use:
str.charAt(index) === '(';
To check if there are brackets at a specific index in the string:
/[()]/.test(str[index])
To check if there are any brackets in the string at all:
/[()]/.test(str)
If you want to test for a specific bracket type (e.g. opening but not closing) remove the other one (e.g. closing) from the regex.
The URL looks like this:
http://www.example.com/?lessoncontent=lesson-003-pinyin
I managed to get the last part with this:
var url = window.location.href.split("/").pop();
So now I got this:
?lessoncontent=lesson-003-pinyin
Not sure how to get the last part, though (pinyin). I want to be able to do if statements with URLs like this:
?lessoncontent=lesson-001-pinyin
?lessoncontent=lesson-003-pinyin
?lessoncontent=lesson-002-complete
?lessoncontent=lesson-003-complete
(Only taking into account the last word of the URL).
Example:
if (match === "pinyin") { //do stuff }
if (match === "complete") { //do stuff }
Just split on - and take the last element from it.
var match = window.location.href.split("-").pop();
if (match === "pinyin") {} // do stuff
if (match === "complete") {} // do stuff
We are splitting on - and then, taking the last element in it by popping it out of the Array.
I would try this:
(\w+)[&?\/]?$
which will work for all sorts of URLs, for example whether there is a URL parameter or not. It will get all the word characters up to a optional trailing &, ?, or /. See Regex 101 Demo here.
[^-]*$
Try this.See demo.You can direclty apply this over the link and get the answer in one step.
https://regex101.com/r/wU7sQ0/16
var re = /[^-]*$/gm;
var str = 'http://www.example.com/?lessoncontent=lesson-003-pinyin';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
You may try RegExp:
var match = location.search.match(/(\w+)$/)[0]
if (match === "pinyin") { //do stuff }
if (match === "complete") { //do stuff }
Here, location.search will only the parameters i.e. ?lessoncontent=lesson-001-pinyin. Next match(/(\w+)$/) gives you an array of matching words from the end of string.
I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.
I'm trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Well, you are using String.search, which, according to the linked documentation:
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
So it will return -1, or 0 or greater when there is a match. So you should test for -1, not truthiness.
Also, there is no need to pass the regexes as strings, you might as well use:
url.replace(/&sort=.*&/i,'&sort='+sort+'&');
Further, keep in mind that replace will create a new string, not replace in the string (strings in Javascript are immutable).
Finally, I don't see the need for searching for the string, and then replacing it -- it seems that you always want to replace &sort=SOMETHING with &sort=SOMETHING_ELSE, so just do that:
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
url = url.replace(/&sort=[^&]*/i, '&sort=' + sort);
}
The javascript string function search() returns -1 if not found, not false. Your code should read:
if(url.search('/&sort=.*&/i') != -1) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i') != -1) {
url.replace('/&sort=.*/i','&sort='+sort);
}
You should check
if(url.search('/&sort=.*&/i') >= 0)
then it should work
You could use this code
var url = 'http://localhost/search?location=any&sort=asc';
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
console.log(vars);
//vars is an object with two properties: location and sort
This can be done by using
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + sort);
The match broken down
Group 1 matches for ? or &
Group 2 matches sort=
Group 3 matches anything that is not a & or ?
Then "$1$2" + sort will replace all 3 group matches with the first 2 + your variable
examples using string "REPLACE" instead of your sort variable
url = "http://localhost/search?location=any&sort=asc&a=z"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE&a=z"
url = "http://localhost/search?location=any&sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE"
url = "http://localhost/search?sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE"
url = "http://localhost/search?sort=asc&z=y"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE&z=y"
The pattern I am using is: &sort=.*& Test URL:
http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on
the basis that their is no ampersand character following the sort
parameter's value?
you are assuming right. But in your code you have else if(url.search('/&sort=.*/i')) which will match and thus still replace the value.
You should also note that your code would turn http://localhost/search?sort=asc&location=any&some=more into http://localhost/search?sort=asc&some=more. that's because because .* is greedy (trying to match as much as possible). You can avoid that by telling it to match as little as possible by appending a ? like so .*?.
That said, I believe you may be better off with a library that knows how URLs actually work. You're not compensating for parameter position, possible escaped values etc. I suggest you have a look at URI.js and replace your wicked regex with
var uri = URI(document.URL),
data = uri.query(true);
data.foo = 'bazbaz';
uri.query(data);
How could I do something like this:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
You need add href property and check indexOf instead of contains
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
}
});
</script>
if (window.location.href.indexOf("franky") != -1)
would do it. Alternatively, you could use a regexp:
if (/franky/.test(window.location.href))
You would use indexOf like this:
if(window.location.href.indexOf("franky") != -1){....}
Also notice the addition of href for the string otherwise you would do:
if(window.location.toString().indexOf("franky") != -1){....}
window.location isn't a String, but it has a toString() method. So you can do it like this:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
From the old Mozilla docs:
Location objects have a toString
method returning the current URL. You
can also assign a string to
window.location. This means that you
can work with window.location as if it
were a string in most cases.
Sometimes, for example when you need
to call a String method on it, you
have to explicitly call toString.
like so:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("cart") > -1)
{
alert("your url contains the name franky");
}
});
</script>
The regex way:
var matches = !!location.href.match(/franky/); //a boolean value now
Or in a simple statement you could use:
if (location.href.match(/franky/)) {
I use this to test whether the website is running locally or on a server:
location.href.match(/(192.168|localhost).*:1337/)
This checks whether the href contains either 192.168 or localhost AND is followed by :1337.
As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.
document.URL should get you the URL and
if(document.URL.indexOf("searchtext") != -1) {
//found
} else {
//nope
}
Try this, it's shorter and works exactly as window.location.href:
if (document.URL.indexOf("franky") > -1) { ... }
also if you want to check the previous URL:
if (document.referrer.indexOf("franky") > -1) { ... }
Easier it gets
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.href;
if(url.includes('franky')) //includes() method determines whether a string contains specified string.
{
alert("url contains franky");
}
});
</script>
It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.
This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:
var string= location.href;
var convertedString= string.toLowerCase();
if(convertedString.indexOf('franky') != -1)
{
alert("url has franky");
}
else
{
alert("url has no franky");
}
I like this approach, instead.
top.location.pathname.includes('franky')
It works in many cases.
Try this:
<script type="text/javascript">
$(document).ready
(
function ()
{
var regExp = /franky/g;
var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
if(regExp.test(testString)) // This doesn't work, any suggestions.
{
alert("your url contains the name franky");
}
}
);
</script>
Try indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
You can also try search (for regular expressions)
if (foo.search("franky") >= 0)
{
...
}
Use Window.location.href to take the url in javascript. it's a
property that will tell you the current URL location of the browser.
Setting the property to something different will redirect the page.
if (window.location.href.indexOf('franky') > -1) {
alert("your url contains the name franky");
}
I like to create a boolean and then use that in a logical if.
//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);
if (!onLoginPage) {
console.log('redirected to login page');
window.location = "/login";
} else {
console.log('already on the login page');
}
Put in your js file
var url = window.location.href;
console.log(url);
console.log(~url.indexOf("#product-consulation"));
if (~url.indexOf("#product-consulation")) {
console.log('YES');
// $('html, body').animate({
// scrollTop: $('#header').offset().top - 80
// }, 1000);
} else {
console.log('NOPE');
}
Regular Expressions will be more optimal for a lot of people because of word boundaries \b or similar devices. Word boundaries occur when any of 0-9, a-z, A-Z, _ are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.
if (location.href.match(/(?:\b|_)franky(?:\b|_)))
If you use if(window.location.href.indexOf("sam"), you'll get matches for flotsam and same, among other words. tom would match tomato and tomorrow, without regex.
Making it case-sensitive is as simple as removing the i.
Further, adding other filters is as easy as
if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))
Let's talk about (?:\b|_). RegEx typically defines _ as a word character so it doesn't cause a word boundary. We use this (?:\b|_) to deal with this. To see if it either finds \b or _ on either side of the string.
Other languages may need to use something like
if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.
All of this is easier than saying
var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it
// more for other filters like frank and billy
Other languages' flavors of Regular Expressions support \p{L} but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]
a window location is an object that contains multiple methods and props some of them is strings related to URL so you can search for the targeted string safely:
const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// another option
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true
The Location Object
Suppose you have this script
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow
The text written to <p id="response"> will be stack
This is my code ♥
function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
return true;
}
else {
console.log("Error", "The link is not valid");
}
return false;}
You can use javascript string method match
const url = window.location.href;
const find = 'questions';
const found = url.match(find);
console.log(url);
if(found !== null && found[0] === find){
console.log('You are in the questions page');
} else {
console.log('You are not in the questions page');
}