Javascript Regular Expression to parse JSON - javascript

I asked a question about regular expression in PHP (which got answered), I need help with same regular expression in javascript, here is the link to previous question. Regular expression to parse JSON
Again I am not looking to get JSON.parse and get the json object, I need to find the regex for the pattern.
Thanks

/\[\[.*?\]\]/g
G - Global (find more than once)

for complex objects, you can further try this -
\{.*\:\{.*\:.*\}\}
{"ABC":{"Prop1":false,"Prop2":"abc","Prop3":false}}
Tested it # http://www.regextester.com/

Try something like:
var matches = text.match(/\[\[.*?\]\]/);
matches[0] will be the matched string.
Since the DOTALL PCRE option isn't supported in Javascript, you'd have to use a regular expression like that:
var matches = text.match(/\[\[(?:\s|.)*?\]\]/);

Related

Regular Expression to find Images links in string

I have a string like this https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500 and I need to define if this image-link or not.
I found regular expression /(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png)/g which define image if link has appropriate format in the end, but this regular expression doesn't work with such link https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500
I am not familiar with regular expressions, so can you help me to improve this regular expression and define such link. Thanks
You need to escape that / in regex, so this is correct
/(http(s?):)([\/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png)/g
Just modify the regular expression like that:
/(http(s?):)([\/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png)/g
You can shorten your existing expression significantly by collapsing some of your capture groups, as well as removing the pipe characters from your [] character set. Characters sets automatically behave like "OR" statements without the use of pipes.
/(https?:)([\/.\w\s-])*\.(?:(jpe?|pn)g|gif)/gi
To dissect this expression and see why it works, take a look at it on RegExr.
That regex is too restrictive because it is poorly performing domain validation so you can loosen it up like this:
https?:\/\/[^.]*?(\.[^.]+?)*\/.*?\.(jpg|jpeg|gif|png)
https://regex101.com/r/ZXyOkQ/2
You can use URL api and test
let str = `https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500`
let str2 = `https://images.pexels.com/photos/459225/pexels-photo-459225.exe?auto=compress&cs=tinysrgb&dpr=1&w=500`
let isImage = (str) =>{
let parsed = new URL(str)
return /(?:jpe?g|gif|png)$/i.test(parsed.pathname)
}
console.log(isImage(str))
console.log(isImage(str2))

JavaScript Regular Expression to get words in quotes string

Thanks for all, I met a problem in JavaScript, and the problem is:
I have a string: such as:
{"results":[{"id":"id1","text":"text1"},{"id":"id2","text":"text2"},{"id":"id3","text":"text3"}]}
Then, I want to get the string such as:
id1|text1|id2|text2|id3|text3
So how should I write the Regular Expression?
Thank you so much, and I am a new comer in StackOverFlow!
I have a string
That string is in JSON format, which works very well with JavaScript.
So how should I write the Regular Expression?
You should not write a regular expression at all. If you did, you only had two problems:
.replace(/(^.+?|"\},\{)?"id":"|","text":"|"}[^"]*$/g, "|").slice(1,-1)
Instead, parse the string into an object, and extract the id-text pairs from there:
var result = JSON.parse(string).results.map(function(el) {
return el.id+"|"+el.text;
}).join("|");

Preparing a regular expression for javascript

I have made this regular expression which does exactly what I want when I test it in e.g. RegExr:
^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?
However when I test it in javascript it says that the expression is invalid. After hours of debugging I found out that this expression works in javascript:
^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?![a-z0-9]+\.)?(localhost|yahoo\.com)(.*)?
However this doesn't do what I want (again testing in RegExr).
Why cannot I use the first expression in javascript? And how do I fix it?
UPDATE JULY 25
Sorry for the lack of info. The way I am using the Regexp is through a jQuery extension which lets me select using regexp. The script can be seen here: http://james.padolsey.com/javascript/regex-selector-for-jquery/
The specific code I am trying to get to work is:
$('a:regex(href, ^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?)').live('click', function(e) {
After including the linked jQuery plugin. The text strings I am testing are:
http://yahoo.com
http://google.dk
http://subdomain.yahoo.com
http://test.yahoo.com
http://localhost.dk
http://sub.yahoo.com/lalala
Where it is supposed to match "http://google.dk", "http://test.yahoo.com" and "http://sub.yahoo.com/lalala" - which it does when using RegExr but failing (invalid expression) using the jQuery plugin.
The first regular expression is not invalid:
var regexp = /^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?/;
works fine.
If you want to instantiate the expression from a string, you have to double all the backslashes:
var regexp = new RegExp("^https?:\\/\\/(www\\.)?(test\\.yahoo\\.com|sub\\.yahoo\\.com)?(?!([a-z0-9]+\\.)?(localhost|yahoo\\.com))(.*)?");
When you start from a string, you have to account for the fact that the string constant itself uses backslashes as a quoting mechanism, so there will be two evaluations made: one as a string, and one as a regular expression.
edit — OK I think I see the problem. That plugin you're trying to use is simply attempting to do something that's just not going to work, given the way that Sizzle parses selectors. In other words, the problem is not with your regular expression, it's with the overall selector. It is not even getting far enough to parse the regular expression.
Specifically it seems to be nested parentheses inside the regular expression. Something as simple as
$('a:regex(href, ((abc)))')
causes an error. You can instead do something like this:
$('a').filter(function() {
return /^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?/.test(this.href);
}).whatever( ... );

Invalid regular expression in javascript

I'm trying to find out if a string contains css code with this expression:
var pattern = new RegExp('\s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1}');
But I get "invalid regular expression" error on the line above...
What's wrong with it?
found the regex here: http://www.catswhocode.com/blog/10-regular-expressions-for-efficient-web-development
It's for PHP but it should work in javascript too, right?
What are the ? at the start of the two [a-zA-z-] blocks for? They look wrong to me.
The ? is unfortunately somewhat overload in regexp syntax, it can have three different meanings that I know of, and none of them match what I see in your example.
Also, your \s sequences need the backslash escaping because this is a string - they should look like \\s. To avoid escaping, just use the /.../ syntax instead of new Regexp("...").
That said, even that is insufficient - the regexp still produces an Invalid Group error in Chrome, probably related to the {1} sequences.
The ?'s are messing it up. I'm not sure what they are for.
/\s[a-zA-Z\-]+\s*:\s*[a-zA-Z0-9\s.#]+;/
worked for me (as far as compiling. I didn't test to see if it properly detected a CSS string).
Replace the quotes with / (slashes):
var pattern = /\s([a-zA-Z-]+)\s[:]{1}\s*([a-zA-Z0-9\s.#]+)[;]{1}/;
You also don't need the new RegExp() part either, which is why it's been removed; instead of using a quote or double quote to denote a string, JavaScript uses a slash / to denote a regular expression, which isn't a normal string.
That regular expression is very bad and I would avoid its source in the future. That said, I cleaned it up a bit and got the following result:
var pattern = /\s(?:[a-zA-Z-]+)\s*:\s*(?:[^;\n\r]+);/;
this matches something that looks like css, for example:
background-color: red;
Here's the fiddle to prove it, though I'd recommend to find a different solution to your problem. This is a very simple regex and it's not save to say that it is reliable.

Regular expression for browser Url

I am new to JavaScript
i need a regular expression which
allows both of this forms
for example :
http://www.google.com
www.google.com
var url_pattern = new RegExp("((ftp|http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?", "i");
return url_pattern.test(url);
(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?
This works quite well.
I've just written up a blog post on recognising URLs in most used formats such as:
www.google.com
http://www.google.com
mailto:somebody#google.com
somebody#google.com
www.url-with-querystring.com/?url=has-querystring
The regular expression used is /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/ however I would recommend you got to http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the to see a complete working example along with an explanation of the regular expression in case you need to extend or tweak it.
^((?:(?:https?|ftp):)?\/\/?)?(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$
Test it! https://regex101.com/r/qQ8uV6/1
Extracted from In search of the perfect URL validation regex https://mathiasbynens.be/demo/url-regex (modified it a bit).
credits to #diegoperini.
If you test it in JavaScript, you'll get a nice
ParseError: Error parsing regular expression: Invalid regular expression
....
Range out of order in character class
You need to replace \x{xxxx} for \uxxxx. So in JavaScript it'll be:
^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\ufff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$
Just like stated in JavaScript Unicode Regex - Range out of order in character class

Categories

Resources