Check if URL contains text and brackets - javascript

I want to check my current URL, for example:
http://www.dummy.com/subpageone/pagetwo.html?ineedthis[andthis]&butnotthis
I want an alert if I got exactly ineedthis[andthis]
So far I got
if (window.location.href.indexOf("ineedthis") > -1) {
alert("your url contains it");
}
However it's not enough. How do I check for the [andthis]? I have tried it with some variations but no luck at all.
indexOf("ineedthis\[andthis\]")
indexOf("ineedthis%5andthis%5D")
if (/ineedthis\[andthis\]/.test(window.location.href))
Thanks for any suggestions.

Simply use:
if(window.location.href.indexOf("ineedthis[andthis]") > -1) {
alert("your url contains it");
}
As searchValue for indexOf is string rather than regular expression.

also you can use Regular expression to do the same:
(function(){
var pattern = new RegExp(/ineedthis\[andthis\]/);
alert(pattern.test('ineedthis[andthis]'));
}());

Related

How to redirect url based on only one part of the path?

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 (/)

how to use regex with user input variable

I am getting an array of objects using JSON and then my goal is to let the user search for a specific login. For this I want them to be able to type a letter and check each object login, if the letter is contained I want to display it.
In order to achieve this I worked on the following code:
var i;
var out="";
var exp=/d/g;
var result = " ";
for(i=0;i<users.length;i++){
result= exp.test(users[i].login);
if(result){
out+= users[i].login+ " ";
}
}
It works fine if I write the regex (in this case d) but once I try putting a variable inside the regex it wont work. How do I create a regex that will take the users input and work with the test function to perform the same task? Or idk if there is a better/more elegant solution for this. I know there are different regex questions already but I didn't find one that helped me.
Appreciate the help!
You're testing a literal string - that string is passed in by the user but it's still literal, not a regex.
So you should try:
if( users[i].login.indexOf(userInput) > -1)
This will pass if the given input is in the searched string.

Using regex in javascript

I cannot get to work the following example of Regex in JavaScript. Regex is valid, was tested on some webs testing Regex expression.
I want it to check if input is in format: xxx,xxx,xxx.
It is alerting wrong input all the time. Thanks for any help.
var re = /[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*/;
var toValidation = document.getElementsByName("txtSerial").value;
alert(toValidation);
if(!re.test(toValidation))
return true;
else
{
alert("Please insert valid text.");
return false;
}
document.getElementsByName("txtSerial") will return all elements by that name (node collection). Node collections do not have an attribute named value, thus, .value will be undefined (as can be seen by your alert).
Depending on your markup, you will want to use
document.getElementById("txtSerial")
or
document.getElementsByName("txtSerial")[0]
(although the last one is certainly not ideal).

jquery check is string is inside a string

I got 2 variables;
value = 'com';
longString= "com-233-123-232-123";
I'd like to check if "value" is inside "longString". I tried using regex with test() but I fail, maybe you know better.
I think the indexOf(substr, [start]) is enough no need to regex.
indexOf(substr, [start])
Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.
http://www.javascriptkit.com/javatutors/string4.shtml
Two ways
1st indexOf
if (longString.indexOf(value) != -1)
// found
else
// not found
2nd split
var value = 'com'; var longString= "com-233-123-232-123";
var split1=longString.split("-");
var i=0;
var found=0;
while (i<split1.length)
{
if(split1[i]==value)
{
found=1;
break;
}
i++;
}
if(found==1)
//found
else
//not found
Don't use regular expressions for this - if the value you're looking for can be interpreted as a regular expression itself then you'll have trouble. Just check for longString.indexOf(value) != -1.
What does jQuery has to do with this? This is a simple Javascript problem
if (longString.indexOf(value) != -1)
// We found it
else
// We didn't find it

How to encode a query string so that it is the value of another query string in javascript?

I have a javascript function which passes as a query string value another query string.
In other words, I want the query string to be:
http://www.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3
However, if I redirect like this:
var url = 'http://www.somesite.com/?somequery=';
url += escape('?key=value1&key2=value2');
window.location = url;
it ends up as http://www.somesite.com?somequery=?key1=value1&key2=value2 in firefox and IE7 which means that I can't parse the query string correctly.
I also tried using encodeURIComponent which didn't work either.
Is there another function or a hack to force the redirect to keep the somequery value escaped??
encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)
var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window.location= uri;
Takes me to:
http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e
When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.
escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.
Native escape method does that. but also you can create a custom encoder like:
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs.
function downloadFile(){
var filePath = "C:/Users/HP/Desktop/Project Folder/DemoProject/";
var fileInfo = "Error_Issue Minor Cosmetic & Major Fatal Issues (Demo_Project) (2017)_GeneratedOn_12_21_2017 21924 AM.xlsx";
if((filePath != undefined && filePath.length > 0) && (fileName != undefined && fileName.length > 0)){
var downloadUrl = "../download?fileName="+encodeURIComponent(fileName)+"&filePath="+encodeURIComponent(filePath);
$window.location = downloadUrl;
}else{
alert("Please define a fileName for downloading...");
}
}
javascript:alert(escape('?key=value1&key2=value2'));
Works fine for me?

Categories