Matching Regular Expression for URLS in JavaScript Produces null - javascript

I have the following regular expression which I have validated:
"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?"
I have the following Javascript code to find regular expressions:
var cTextVal = "This URL should match http://google.com";
var regEx = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?"
var matches = cTextVal.match(regEx);
alert(matches); // This produces null
How do I find the string that matches this regular expression in JavaScript?
Update Based on Comments:
This crashes my code:
var regEx = /(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/g
This produces null:
var regEx = "/(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/g"

Escape forward slashes before second capture group
var regEx = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/;
var cTextVal = "This URL should match http://google.com";
var matches = cTextVal.match(regEx).shift();
console.log(matches);

Related

jQuery regex replace return replacing word

I have a string (url) like this:
https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/
Here is my regex:
/https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi
And my code:
var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/";
var myRegexp = /https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi
var match = string.replace(myRegexp, "OMEGA3");
When I do console.log(match) it returns only "OMEGA3". What I want is just my string with "undefined" replaced by "OMEGA3". What am I doing wrong? Thanks.
You can use this regex with capturing groups and back-reference:
url = url.replace(/(https?:\/\/[^\/]*\/g\/[^\/]*\/[^\/]*\/).*(\/codec\/)/gi, '$1OMEGA3$2');
RegEx Demo
You have the use of the capture group backwards. You should be capturing the parts of the pattern that you want to keep, not the part you want to replace. Then use $1, $2, etc. to copy those to the replacement.
You also have several non-capturing groups that aren't needed at all.
var myRegexp = /(https:\/\/.*\/g\/.*\/).*(\/codec\/)/gi
var match = string.replace(myRegexp, "$1OMEGA3$2");
why not use /undefined/gi
var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/";
var myRegexp = /(https\:\/\/.*?\/.*?\/.*?\/.*?\/).*?(\/.*?\/)/gi
var match = string.replace(myRegexp, "$1OMEGA3$2");
console.log(match)

Regexp with .exec not working

I want to match 3 letters and 3 digits with regexp and exec. But I dont get any result. Any idea what is wrong? The code is:
var regnr = "This is the pattern to match: WBJ124";
var patt = new RegExp("^\b[a-zA-Z]{3}\d{3}\b*$");
var sequence = '';
var grps = patt.exec(regnr);
if(grps!=null){
sequence = grps[0];
}
sequence is empty, but I expect it to be WBJ124
Best Regards
You have few mistakes in your regex like using ^ and $ when you are matching a substring in a longer string. Also you are using RegExp object that accepts a string literal hence requires double escaping.
You can use:
var regnr = "This is the pattern to match: WBJ124";
var patt = /\b[a-zA-Z]{3}\d{3}\b/; // or new RegExp("\\b[a-zA-Z]{3}\\d{3}\\b")
var grps = patt.exec(regnr);

Regex working fine in C# but not in Javascript

I have the following javascript code:
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)");
var matches = latexRegex.exec(markdown);
alert(matches[0]);
matches has only matches[0] = "x=1 and y=2" and should be:
matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"
But this regex works fine in C#.
Any idea why this happens?
Thank You,
Miguel
Specify g flag to match multiple times.
Use String.match instead of RegExp.exec.
Using regular expression literal (/.../), you don't need to escape \.
* matches greedily. Use non-greedy version: *?
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = /\[.*?\]|\(.*?\)/g;
var matches = markdown.match(latexRegex);
matches // => ["(x=1)", "(y=2)", "[z=3]"]
Try non-greedy: \\\[.*?\\\]|\\\(.*?\\\). You need to also use a loop if using the .exec() method like so:
var res, matches = [], string = 'I have \(x=1\) and \(y=2\) and even \[z=3\]';
var exp = new RegExp('\\\[.*?\\\]|\\\(.*?\\\)', 'g');
while (res = exp.exec(string)) {
matches.push(res[0]);
}
console.log(matches);
Try using the match function instead of the exec function. exec only returns the first string it finds, match returns them all, if the global flag is set.
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]";
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)", "g");
var matches = markdown.match(latexRegex);
alert(matches[0]);
alert(matches[1]);
If you don't want to get \(x=1\) and \(y=2\) as a match, you will need to use non-greedy operators (*?) instead of greedy operators (*). Your RegExp will become:
var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");

Replace string that starts with specific character and ends with specific character in regular expression

I wanted to replace a string section that starts with a specific character and ends with specific character. At below, I demonstrate test case.
var reg = /pattern/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
console.log(test);
This pattern should work for replace anything between brackets (including the brackets):
var reg = /(\[.*?\])/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
based on your example, this works:
/\[.*]/gi

Javascript regex to bring back all symbol matches?

I need a javascript regex object that brings back any matches of symbols in a string,
take for example the following string:
input = !"£$[]{}%^&*:#\~#';/.,<>\|¬`
then the following code:
input.match(regExObj,"g");
would return an array of matches:
[[,!,",£,$,%,^,&,*,:,#,~,#,',;,/,.,,,<,>,\,|,¬,`,]]
I have tried the following with no luck.
match(/[U+0021-U+0027]/g);
and I cannot use the following because I need to allow none ascii chars, for example Chinese characters.
[^0-9a-zA-Z\s]
var re = /[!"\[\]{}%^&*:#~#';/.<>\\|`]/g;
var matches = [];
var someString = "aejih!\"£$[]{}%^&*:#\~#';/.,<>\\|¬`oejtoj%";
while(match = re.exec(someString)) {
matches.push(match[1]);
}
Getting
['!','"','[',']','{','}','%','^','&','*',':','#','~','#',''',';','/','.','<','>','\','|','`','%]
What about
/[!"£$\[\]{}%^&*:#\\~#';\/.,<>|¬`]/g
?

Categories

Resources