Shouldn't this RegExp work? - javascript

testString = "something://something/task?type=Checkin";
patt = new RegExp("something\/(\w*)\?");
match = patt.exec(testString);
document.querySelector('#resultRegexp').innerHTML = match[1];
I want to capture task So shouldn't this RegExp work?
I am grabbing any alphanumeric character up until the question mark... and capturing it.
http://jsfiddle.net/h4yhc/2/

You would need to escape the slash in regex literals, and the backslash in string literals which you create regexes from:
var patt = /something\/(\w*)\?/g;
// or
var patt = new RegExp("something/(\\w*)\\?", 'g');
I strongly recommend the first version, it is more readable.

I think this would be enough: (\w*)\?, since / is not captured by \w and the only ? in the string is after your target string.

This is what you need:
patt = new RegExp(".*/(\\w*)\\?");
http://jsfiddle.net/FJcfd/

try with this: var pat = /something:\/\/(?:[^\/]+\/)+(\w+)\?(\w+=\w+)/;
it can match string such as:
something://something/task?type=Checkin
something://something/foo/task?type=Checkin
something://something/foo/bar/task1?type3=Checkin4

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)

Add variable into string

All I need to do here is to add a variable before each specific string.
Example:
var exampleString = "blabla:test abcde 123test:123";
var formattedString = "el.blabla:test abcde el.123test:123";
As you can see, when I have something like "XXX:XXX", I need to add a variable before it.
I have the Regex to find "XXX:"
var regex = new RegExp(/\w+([aA-zZ]:)/g)
But when I try to replace it, it replaces all instead of adding the variable "el."
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(new RegExp(/\w+([aA-zZ]:)/g), 'el.');
// formattedString is now "el.test abcde el.123"
// Instead of "el.blabla:test abcde el.123test:123"
Could anyone makes this work ? Thanks :)
Source: Javascript Regex: How to put a variable inside a regular expression?
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/\w*:\w*/gi, 'el.$&');
console.log(formattedString);
Regex use and Explanation Here https://regex101.com/r/U2KeXi/3
Sample Fiddle here https://jsfiddle.net/a8wyLb0g/2/
You need to use ^ to match only at the beginning. And remove the g modifier, since you only want to replace once, not every time.
There's also no reason to use new RegExp(), just use a RegExp literal.
In the replacement string, you need to use $& to copy the original string into the replacement.
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/^\w+[a-z]:/i, 'el.$&');
console.log(formattedString);
Also, the proper way to match all letters in either case is with [A-Za-z], not [aA-zZ], or use the i modifier to make the regexp case-insensitive. Your regexp matches all characters in the range A-z, which includes lots of punctuation characters that are between the uppercase letters and lowercase letters in the ASCII code.
Just use this
exampleString.replace(/(\w*):(\w*)/gi, 'el.$1:$2');
REGEXP explanation :
capturing group (\w*) is for capturing any alphabets in any number of occurance,
$1 and $2 specifies the first and second capturing group.
You should use a function like insertAt instead replace, see following example:
String.prototype.insertAt=function(index, string) {
return this.substr(0, index) + string + this.substr(index);
}
var exampleString = "blabla:test abcde 123test:123";
var regex = new RegExp(/\w+([aA-zZ]:)/g)
var formattedString = exampleString;
while ( (result = regex.exec(exampleString)) ) {
formattedString = formattedString.insertAt(result.index, "el.");
}
console.log(formattedString);
I hope it helps you, bye.

Use regex to remove "public://" from string

Im lost in part of this.
I want to remove the public:// in every link of an image like public://china-taxi_4.jpg
I have tried this but returns null:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
Hope you can help.
I want to remove the 'public://' in every link of an image.
> var img = 'public://china-taxi_4.jpg';
> img.replace(/public:\/\/(?=\S+?\.jpg(?:\s|$))/, "")
'china-taxi_4.jpg'
It removes the word public:// only in the strings which ends with .jpg
You are removing a literal string, not a regular expression. So try:
var _img = 'public://china-taxi_4.jpg';
var result = _img.replace("public://","");
console.log(result);
Regexes are for matching complex expressions.
I think you're missing a slash, try:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
From Mozilla Developer Network String.prototype.replace():
Example: Defining the regular expression in replace()
In the following example, the regular expression is defined in
replace() and includes the ignore case flag.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);
This prints:
'Twas the night before Christmas...'
To match the beginning of a string, use ^
To escape characters that have special meaning in regexp like : and / so that regexp will match these literally, prepend \
This suggests:
var _img = 'public://china-taxi_4.jpg';
var newimg = _img.replace(/^public\:\/\//i, '');
Tested and working in chrome browser console window.
Note: This answer also matches an earlier comment by #dystroy, so I have marked it CW.
var re = /(public:)(\/\/[\w-.]+)/g;
See demo.
http://regex101.com/r/rA7aS3/9

Javascript regexp does not work

Test string is "page-42440233_45778105"
pattern "(page-\d+_\d+)"
Online tester(http://www.regexr.com/) successfuly finded mathc,but in browser js result is null. Why?
var re = new RegExp("(page-\d+_\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
I think this would be a better pattern
var re = /^page-\d+_\d+$/i;
It also matches the beginning (^) and end ($) of the string
message.match(re);
//=> ["page-42440233_45778105"]
You need to escape \ if you use string literal:
var message = "page-42440233_45778105";
var re = new RegExp("(page-\\d+_\\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
// => ["page-42440233_45778105"]
More preferably, use regular expression literal:
var re = /(page-\d+_\d+)/gim;
When you use a string literal, you must escape the \ :
var re = new RegExp("(page-\\d+_\\d+)", "gim");
A better solution here would be to use a regex literal :
var re = /(page-\d+_\d+)/gim
Don't use the RegExp constructor if the regular expression is constant, regex literals are much more convenient.

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

Categories

Resources