Regular Expression to find Images links in string - javascript

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

Related

JavaScript RegEx match unless wrapped with [nocode][/nocode] tags

My current code is:
var user_pattern = this.settings.tag;
user_pattern = user_pattern.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // escape regex
var pattern = new RegExp(user_pattern.replace(/%USERNAME%/i, "(\\S+)"), "ig");
Where this.settings.tag is a string such as "[user=%USERNAME%]" or "#%USERNAME%". The code uses pattern.exec(str) to find any username in the corresponding tag and works perfectly fine. For example, if str = "Hello, [user=test]" then pattern.exec(str) will find test.
This works fine, but I want to be able to stop it from matching if the string is wrapped in [nocode][/nocode] tags. For example, if str = "[nocode]Hello, [user=test], how are you?[/nocode]" thenpattern.exec(str)` should not match anything.
I'm not quite sure where to start. I tried using a (?![nocode]) before and after the pattern, but to no avail. Any help would be great.
I would just test if the string starts with [nocode] first:
/^\[nocode\]/.test('[nocode]');
Then simply do not process it.
Maybe filter out [nocode] before trying to find the username(s)?
pattern.exec(str.replace(/\[nocode\](.*)\[\/nocode\]/g,''));
I know this isn't exactly what you asked for because now you have to use two separate regular expressions, however code readability is important too and doing it this way is definitely better in that aspect. Hope this helps 😉
JSFiddle: http://jsfiddle.net/1f485Lda/1/
It's based on this: Regular Expression to get a string between two strings in Javascript

Non-capturing groups in Javascript regex

I am matching a string in Javascript against the following regex:
(?:new\s)(.*)(?:[:])
The string I use the function on is "new Tag:var;"
What it suppod to return is only "Tag" but instead it returns an array containing "new Tag:" and the desired result as well.
I found out that I might need to use a lookbehind instead but since it is not supported in Javascript I am a bit lost.
Thank you in advance!
Well, I don't really get why you make such a complicated regexp for what you want to extract:
(?:new\\s)(.*)(?:[:])
whereas it can be solved using the following:
s = "new Tag:";
var out = s.replace(/new\s([^:]*):.*;/, "$1")
where you got only one capturing group which is the one you're looking for.
\\s (double escaping) is only needed for creating RegExp instance.
Also your regex is using greedy pattern in .* which may be matching more than desired.
Make it non-greedy:
(?:new\s)(.*?)(?:[:])
OR better use negation:
(?:new\s)([^:]*)(?:[:])

Getting this regex expression to work in javascript

I have an html checkbox element with the following name:
type_config[selected_licenses][CC BY-NC-ND 3.0]
I would like to break this name apart as follows and returned as part of an array:
["type_config", "[selected_licenses]", "[CC BY-NC-ND 3.0]", "[selected_licenses][CC BY-NC-ND 3.0]"]
I thought I could do this by using a regular expression in javascript. Here is the expression that I am using:
matches = /([a-zA-Z0-9_]*)((\[[a-zA-Z0-9_\.\s]*\])+)*/.exec(element_name);
but this is the result I am getting in my matches variable:
["type_config[selected_licenses]", "type_config", "[selected_licenses]", "[selected_licenses]", index: 0, input: "type_config[selected_licenses][CC BY-ND 3.0]"]
I am half way there. What am I doing wrong in my regular expression? I guess I should also ask if it is possible to accomplish what I want with a regex?
Thanks.
The problem with this kind of goal is that there's no simple way to achieve this with regular expression, i.e. a simple match call. In short, even if you put a quantifier after a capturing group, the captured string will always be just one.
You'll have to rely on something more specific, like breaking the string with a repeated use of indexOf, or something like
name.split(/(?=\[)/);
Maybe you want to be sure that name is formally correct.
This is a very ugly problem. I don't know how repeatable this is, but I can do it:
Regex
^(\w+)(?<firstbracket>\[(?<secondbracket>[^]]*)\]\[(.*?)\])$
Replacement
["$1", "[$3]", "[$4]", "$2"]
Demo
http://regex101.com/r/eD9mH8

js: special char in regex

in my regular expression, I tried to remove all "{" and "}"s from a string.
Pushing the script with packer/minimizer scripts, breaks them.
That's why I'd like to know about a better and more compatible way of writing:
mystring.replace(/\{/g,"");?
You can just use a string instead of a regex. I'm not sure if this is "better" but it should not break when minified. If you provide the minified example, we may be able to help with that.
mystring.replace("}", "").replace("{", "");
Edit:
If the curly bracket is causing the problem, perhaps this would work...
var reg = new RegExp("\\{|\\}", "g");
mystring.replace(reg, "");
Example from the console...
> var mystring = "test{foo}bar{baz}";
> var reg = new RegExp("\\{|\\}", "g");
> mystring.replace(reg, "");
"testfoobarbaz"
Lastly, you could do this:
If a regex really wont work for you, this will replace all {'s and }'s
It is probably a horrible solution, considering performance, but...
mystring.split("}").join("").split("{").join("");
You could try
mystring.replace(/\u007B/g,"");
This uses unicode rather than the actual symbol, so your packer won't get confused. If you want to replace more than one character in a single statement, you can use the "or" pipe:
mystring.replace(/\u007B|\u007D/g,"");
{ = \u007B
} = \u007D
For more unicode codes see:
http://www.unicode.org/charts/PDF/U0000.pdf
After re-reading the question, it sounds like you've found a bug with the minifier/packer. My first suggestion would be to use a better minimizer that doesn't have these issues, but if you're stuck with what you're using, you could try using the unicode escape sequence in the regular expression:
mystring.replace(/\u007b/g, '');
Alternatively, you could try String.prototype.split and Array.prototype.join:
mystring.split('{').join('');

Javascript Regular Expression to parse JSON

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|.)*?\]\]/);

Categories

Resources