I'm trying to retrieve the category part this string "property_id=516&category=featured-properties", so the result should be "featured-properties", and I came up with a regular expression and tested it on this website http://gskinner.com/RegExr/, and it worked as expected, but when I added the regular expression to my javascript code, I had a "Invalid regular expression" error, can anyone tell me what is messing up this code?
Thanks!
var url = "property_id=516&category=featured-properties"
var urlRE = url.match('(?<=(category=))[a-z-]+');
alert(urlRE[0]);
Positive lookbehinds (your ?<=) are not supported in JavaScript environments that do not comply with ECMAScript 2018 standard, which is causing your RegEx to fail.
You can mimic them in a whole bunch of different ways, but this might be a simpler RegEx to get the job done for you:
var url = "property_id=516&category=featured-properties"
var urlRE = url.match(/category=([^&]+)/);
// urlRE => ["category=featured-properties","featured-properties"]
// urlRE[1] => "featured-properties"
That's a super-simple example, but searching StackOverflow for a RegEx pattern to parse URL parameters will turn up more robust examples if you need them.
The syntax is messing up your code.
var urlRE = url.match(/category=([a-z-]+)/);
alert(urlRE[1]);
If you want to parse URL parameters, you can use the getParameterByName() function from this site:
http://james.padolsey.com/javascript/bujs-1-getparameterbyname/
In any case, as already mentioned, regular expressions in JavaScript are not plain strings:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
var url = "property_id=516&category=featured-properties",
urlRE = url.match(/(category=)([a-z-]+)/i); //don't forget i if you want to match also uppercase letters in category "property_id=516&category=Featured-Properties"
//urlRE = url.match(/(?<=(category=))[a-z-]+/i); //this is a mess
alert(urlRE[2]);
Related
I got a web application and an Android app in which I want to check the input.
Now I created this Regex in Java:
private static final String NAME_REGEX = "^[\\w ]+$";
if (!Pattern.matches(NAME_REGEX, name)) {
mNameView.setError(getString(R.string.error_field_noname));
focusView = mNameView;
cancel = true;
}
In JavaScript I want to test the same so I used:
var re = /^[\w ]+$/;
if (!re.test(company)) {
...
}
Everything works fine except that the Java version accepts the characters ä,ö,ü, ó, á (...) and the JavaScript version won't.
Don't know where's the difference between the code mentioned above?
In the end the most important thing is that both (JavaScript and Java) work exactly the same.
Goal:
Get a regex for Javascript that is exactly the same as in Java (^[\\w ]+$)
Please use following regular expression.
var re=^[äöüß]*$
The above regular expression will allow these characters also.
If you want to use special characters and alphabets use the below one
var re=^[A-Za-z0-9!##$%^&*äöüß()_]*$
Try this : /^[\wäöüß ]+$/i.
Please note the modifier i for "case insensitive", or it will not match ÄÖÜ.
These languages uses different engines to read the RegExp. Java supports unicode better than JavaScript does.
See : https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines#Part_2
So state of art is that one must use a library to get the same results in javascript as in java.
As this isn't a real solution for me I simply use this in JavaScript:
var re = /^[A-Za-z0-9_öäüÖÄÜß ]+$/;
and this one in Java:
private static final String NAME_REGEX = "^[A-Za-z0-9_öäüÖÄÜß ]+$";
So this seems to be the exact same in both environments.
Thanks for the help!
I'm trying to use this great RegEx presented here for grabbing a video id from any youtube type url:
parse youtube video id using preg_match
// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();
var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;
console.log('vid: '+videoId);
My console is always giving me a null videoId though. Am I incorrectly escaping something in my regexp var? I added the a second backslash to escape the single backslashes already.
Scratching my head?
% are delimiters for the PHP you got the link from, Javascript does not expect delimiters when using new RegExp(). Also, it looks like \\. should probably be replaced with \. Try:
var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');
Also, you can create a regular expression literally by using Javascript's /.../ delimiters, but then you'll need to escape all of your /s:
var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;
Documentation
Update:
A quick update to address the comment on efficiency for literal expressions (/ab+c/) vs. constructors (new RegExp("ab+c")). The documentation says:
Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.
And:
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Since your expression will always be static, I would say creating it literally (the second example) would be slightly faster since it is compiled when loaded (however, don't confuse this into thinking it won't be creating a RegExp object). This small difference is confirmed with a quick benchmark test.
I developed a javascript function to clean a range of Unicode characters. For example, "ñeóñú a1.txt" => "neonu a1.txt". For this, I used a regular expression:
var = new RegExp patternA ("[\\u0300-\\u036F]", "g");
name = name.replace (patternA,'');
But it does not work properly in IE. If my research is correct, IE does not detect Unicode in the same way. I'm trying to make an equivalent function using the library XRegExp (http://xregexp.com/), which is compatible with all browsers, but I don't know how to write the Unicode pattern so XRegExp works in IE.
One of the failed attemps:
XRegExp.replace(name,'\\u0300-\\u036F','');
How can I build this pattern?
The value provided as the XRegExp.replace method's second argument should be a regular expression object, not a string. The regex can be built by the XRegExp or the native RegExp constructor. Thus, the following two lines are equivalent:
name = name.replace(/[\u0300-\u036F]/g, '');
// Is equivalent to:
name = XRegExp.replace(name, /[\u0300-\u036F]/g, '');
The following line you wrote, however, is not valid:
var = new RegExp patternA ("[\\u0300-\\u036F]", "g");
Instead, it should be:
var patternA = new RegExp ("[\\u0300-\\u036F]", "g");
I don't know if that is the source of your problem, but perhaps. For the record, IE's Unicode support is as good or better than other browsers.
XRegExp can let you identify your block by name, rather than using magic numbers. XRegExp('[\\u0300-\\u036F]') and XRegExp('\\p{InCombiningDiacriticalMarks}') are exactly equivalent. However, the marks in that block are a small subset of all combining marks. You might actually want to match something like XRegExp('\\p{M}'). However, note that simply removing marks like you're doing is not a safe way to remove diacritics. Generally, what you're trying to do is a bad idea and should be avoided, since it will often lead to wrong or unintelligible results.
I have an input field where the user enters a time in format mm:hh. The format is specified inside the field (default value 09:00) but I still want to perform a client-side check to see if the format is correct.
Since the existing client-side validation is in jQuery, I'd like to keep this in jQuery as well.
I'm mainly a PHP programmer so I need some help writing this one in an optimal manner.
I know I can check each individual character (first two = digits, third = ':', last two = digits) but is there a way to do it more elegantly, while also checking the hour count is not larger than 23 and the minute count isn't larger than 59?
In PHP I would use regular expressions, I assume there's something similar for jQuery?
Something like this makes sense to me:
([01]?[0-9]|2[0-3]):[0-5][0-9]
But I'm not too familiar with jQuery syntax so I'm not sure what to do with it.
you can use regex in JavaScript too:
http://www.w3schools.com/jsref/jsref_obj_string.asp
use
.search() - http://www.w3schools.com/jsref/jsref_search.asp
or .match() - http://www.w3schools.com/jsref/jsref_match.asp
or .replace() - http://www.w3schools.com/jsref/jsref_replace.asp
EDIT:
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = ($('input').val().search(regexp) >= 0) ? true : false;
</script>
EDIT2:
here the documentation of regexpobject in javascript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = regexp.test($('input').val());
</script>
EDIT3:
fixed the regexp
In JavaScript, regexes are delimited by /. So you would do...
var isValidTime = /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(inputString);
Your regex seems to make sense for validating any 24H time in HH:mm format. However as I state in my comment under Andreas's answer - this will return true if any part of the string matches. To make it validate the entire string, use anchors to match the start and end of the string also eg...
var isValidTime = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(inputString);
To actually pull the matches you would need to use the string.match JS function.
Oh - and please be aware that jQuery is Javascript - it's just a library of very useful stuff! However this example contains no reference to the jQuery library.
In JavaScript you can use yourstring.match(regexp) to match a string against a regular expression.
I have very limited RegEx-experience, so I cant help you with the pattern, but if you have that set .match() should be all it takes.
A different approach, but using an extra javascript lib instead of regular expressions:
var valid = moment(timeStr, "HH:mm", true).isValid();
I guess if you already use moment.js in your project, there's no downside.
And since you didn't specifically request an answer using regular expressions, I think it's valid to mention.
Does anyone know how to find regular expression string from javascript code?
e.g.
var pattern = /some regular expression/;
Is it possible to to with regular expression :) ?
If I got your question right, and you need a regular expression which would find all the regular expressions in a JavaScript program, then I don't think it is possible. A regular expression in JavaScript does not have to use the // syntax, it can be defined as a string. Even a full-blown JavaScript parser would not be smart enough to detect a regular expression here, for instance:
var re = "abcde";
var regexClass = function() { return RegExp; }
var regex = new regexClass()(re);
So I would give up this idea unless you want to cover only a few very basic cases.
You want a regex to match a regex? Crazy. This might cover the simplest cases.
new RegExp("\/.+\/")
However, I peeked into the Javascript Textmate bundle and is has 2 regex for finding a regex start and end.
begin = '(?<=[=(:]|^|return)\s*(/)(?![/*+{}?])'
end = '(/)[igm]*';
Which you could probably use as inspiration for toward your goal.
Thanks for answers I have found also that it is nearly impossible task to do, but here is my regex which parses source code just fine:
this.mainPattern = new RegExp(//single line comment
"(?://.*$)|"+
//multiline comment
"(/\\*.*?($|\\*/))"+
//single or double quote strings
"|(?:(?:\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|(?:'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'))"+
//regular expression literal in javascript code
"|(?:(?:[/].+[/])[img]?[\\s]?(?=[;]|[,]|[)]))"+
//brackets
"|([{]|[(]|[\[])|([}]|[)]|[\\]])", 'g');