Regex to validate URL hash not working in Javascript - javascript

I have the following code for checking the URL hash part and extract the query strings.
var getCleanHash = function(){
return (/^[a-z-_&=\d]*$/.test(location.hash.substr(1))) ? location.hash.substr(1) : "";
}
so the regex used here is /^[a-z-_&=\d]*$/, but if I have the query strings like type=mytype&q=search, it is returning empty value. If I remove the ^ from the regex, it starts returning the query strings. But then it will not perform any checks as intended in regex. I suppose ^ denotes the first character, but not entirely sure why it doesn't match with my query string part.
Can someone help me to find what this Regex actually means and how can I fix the issue with empty query strings?

var getCleanHash = function(){
return (/^[a-z\d\-_&\=]*$/.test(location.hash.substring(1))) ? location.hash.substring(1) : "";
}
I think you should use .substring(1) instead of .substr(1)
[a-z\d-_&=]* means you are testing:
for any hash even empty ones on the entire length(from start ^ to end $)
a to z and digits plus the following characters(-_&=)

Related

Allowed Characters Regex (JavaScript)

I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101

Regular expression matching javascript

I have a variable which can get any of the below values. x represents any alphanumeric character and the string can be of any length
/xxxxxxx
/xxxx/xxxx?xxx=xx
/xxxxx/
/xxxxxxxxx?
/xxxxxxx/xxxx/xxx
/xx/xxx.jpg
/xxx/xxxx/xxxx/xxxx
/xxx/xxxx/xxx/xxx/xxxx
/xxxx?xx=yy&abc=def&xyz=lmn
The goal is to get everything before the "?" character in the string if ? character exists
if it doesn't exist then it should simply get the string
i have written a regular expression as follows:
var pattern = /\/.*\?/;
The only issue is this pattern does not stop at the ? and return the whole string. Any clues how this can be fixed ?
The goal is to get everything before the "?" character in the string if ? character exists if it doesn't exist then it should simply get the string
/^[^?]*/
This works because ^ means start of input, and [^?] means a character that is not a ?, and * means zero or more, so the whole means "starting from input, zero or more characters that are not question marks".
That has the effect of matching from the start of the input to the first question mark or the end of input whichever comes first.
Something like this should work...
var pattern = /\/.*?(\?|$)/;
You don't really need a regex here, you could simply use indexOf() and substr():
var qPos = url.indexOf('?');
var path = (qPos === -1) ? url : url.substring(0, qPos);

How to regex test a string for a pattern while excluding certain characters?

I'm getting nowhere with this...
I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:
var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";
console.log(re.test(s)) // true
Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?
While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.
/^[^\/]*%2[^\/]*$/
EDIT: Too late... Oh well :P
Try the following:
^(?!.*/).*%2
either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?
or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:
var s = "test/";
if(s.indexOf("/")!=-1){
//contains "/"
}else {
//doesn't contain "/"
}

Extracting numbers from a string using regular expressions

I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"

remove all but a specific portion of a string in javascript

I am writing a little app for Sharepoint. I am trying to extract some text from the middle of a field that is returned:
var ows_MetaInfo="1;#Subject:SW|NameOfADocument
vti_parservers:SR|23.0.0.6421
ContentTypeID:SW|0x0101001DB26Cf25E4F31488B7333256A77D2CA
vti_cachedtitle:SR|NameOfADocument
vti_title:SR|ATitleOfADocument
_Author:SW:|TheNameOfOurCompany
_Category:SW|
ContentType:SW|Document
vti_author::SR|mrwienerdog
_Comments:SW|This is very much the string I need extracted
vti_categories:VW|
vtiapprovallevel:SR|
vti_modifiedby:SR|mrwienerdog
vti_assignedto:SR|
Keywords:SW|Project Name
ContentType _Comments"
So......All I want returned is "This is very much the string I need extracted"
Do I need a regex and a string replace? How would you write the regex?
Yes, you can use a regular expression for this (this is the sort of thing they are good for). Assuming you always want the string after the pipe (|) on the line starting with "_Comments:SW|", here's how you can extract it:
var matchresult = ows_MetaInfo.match(/^_Comments:SW\|(.*)$/m);
var comment = (matchresult==null) ? "" : matchresult[1];
Note that the .match() method of the String object returns an array. The first (index 0) element will be the entire match (here, we the entire match is the whole line, as we anchored it with ^ and $; note that adding the "m" after the regex makes this a multiline regex, allowing us to match the start and end of any line within the multi-line input), and the rest of the array are the submatches that we capture using parenthesis. Above we've captured the part of the line that you want, so that will present in the second item in the array (index 1).
If there is no match ("_Comments:SW|" doesnt appear in ows_MetaInfo), then .match() will return null, which is why we test it before pulling out the comment.
If you need to adjust the regex for other scenarios, have a look at the Regex docs on Mozilla Dev Network: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You can use this code:
var match = ows_MetaInfo.match(/_Comments:SW\|([^\n]+)/);
if (match)
document.writeln(match[1]);
I'm far from competent with RegEx, so here is my RegEx-less solution. See comments for further detail.
var extractedText = ExtractText(ows_MetaInfo);
function ExtractText(arg) {
// Use the pipe delimiter to turn the string into an array
var aryValues = ows_MetaInfo.split("|");
// Find the portion of the array that contains "vti_categories:VW"
for (var i = 0; i < aryValues.length; i++) {
if (aryValues[i].search("vti_categories:VW") != -1)
return aryValues[i].replace("vti_categories:VW", "");
}
return null;
}​
Here's a working fiddle to demonstrate.

Categories