What is the JavaScript equivalent of this .NET code?
var b = Regex.IsMatch(txt, pattern);
Here are the useful functions for working with regexes.
exec A RegExp method that executes a search for a match in a string. It returns an array of information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.
Source: MDC
So to answer your question, as the others have said:
/pattern/.test(txt)
Or, if it is more convenient for your particular use, this is equivalent:
txt.search(/pattern/) !== -1
var b = /pattern/.test(txt);
/pattern/.test(txt);
E.g.:
/foo \w+/.test("foo bar");
It returns true for a match, just like IsMatch.
var regex = new RegExp(pattern);
var b = regex.test(text);
You can also use var b = /pattern/.test(text) but then you can't use a variable for the regex pattern.
Related
I can get the source of a regex when it's defined separately. For example:
let r1 = new RegExp("el*");
console.log(r1.source);
// el*
Or:
let r2 = /el*/;
console.log(r2.source);
// el*
Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:
let m = "Hello".match(/el*/);
console.log(m.source?);
No,
quoting the documents of the match() function
Return value
An Array whose contents depend on the presence or absence of the
global (g) flag, or null if no matches are found.
So the return value is an array (you can test it by Array.isArray(m)// true)
However, the returned array has some extra information about the ocurred match (like groups, index and original input) but none of them include the original regex used to get the match
So there is no way to get that information from the match because its not returned by the matching function
The match result by itself cannot lead to the original regex, simply because different regexes can lead to the same result, even on the same string. Take for example the string "abcd" - all the following regexes: /abcd/, /a..d/ /a.*/ and many more, would match the string exactly the same way.
The only way you could retrive the original regex is if a reference to the regex was literally stored by the match() method inside the returned object. There is no reason to think that's the case, but you can implement your own match function that would do. Something like
function myMatch(str, regex) {
var match = str.match(regex);
if (match === null) {
match = [null];
}
match.source = regex;
return match;
}
In the past, I had this regex:
\{(.*?)\}
And entered this string:
logs/{thing:hi}/{thing:hello}
Then I used the following:
console.log(string.split(regex).filter((_, i) => i % 2 === 1));
To get this result:
thing:hi
thing:hello
For irrelevant design reasons, I changed my regex to:
\{.*?\}
But now, when using the same test string and split command, it returns only this:
/
I want it to return this:
{thing:hi}
{thing:hello}
How can I modify the split (or anything else) to do this?
Why not use match?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
The match() method retrieves the matches when matching a string against a regular expression.
If you're only interested in returning the two string matches then it's much simpler than using split.
var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));
In the tutorial of http://tryregex.com/ i faced the question below:
Write a regular expression which extracts everything between the opening bracket and the closing bracket of the shortStory variable (note that you can view the contents of the variable just by typing shortStory). Hint: you'll need the previously mentioned dot operator.
and shortStory is:
"A regular expression (also regex or regexp) is a string."
I wonder which method in javascript can extract data using regexp? something like SOMEMETHOD in below:
var pat = /\(.+\)/;
shortStory.SOMEMETHOD(pat);
Taken from MDN :
exec : A RegExp method that executes a search for a match in a string. It returns an array of information.
test : A RegExp method that tests for a match in a string. It returns true or false.
match : A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search : A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace : A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split : A String method that uses a regular expression or a fixed string to break a string into an array of substrings.
The last 4 follow this format: String.method(regex)
edit: Here's an example -
'fat car'.search(/(car)/)
this returns 4
'fat car'.replace(/(car)/, 'fish')
this returns "fat fish"
'fat car'.match(/(car)/)
this returns ["car", "car"]
'fat car'.match(/(cat)/)
this returns null
The String is - Success0 or Success7 or any digit.I tried with -
console.log(str.match("Success"+/\d/));
But it is logging null. Any help?
Your regex in .match() isnt right.
Do:
var str = "Success123";
alert(str.match(/^Success\d+$/)); // returns the string if it is a match, otherwise null
Note that if you are just testing the string if it has Success at the begining, you should be using .test(). .match() takes a toll on the browser as compared to .test().
var str = "Success123";
alert(/^Success\d+$/.test(str)); // returns true/false
Regex /^Success\d+$/ explained here.
Readup:
.test() | MDN
.match() | MDN
Try this instead:
str.match(/Success\d+/)
Assuming you are having numbers and it's the whole string :
str.match(/^Success\d+$/)
Ir you want to build up your regex :
var r= new RegExp("^Success"+'\\d+$')
console.log(r.test('Success232'));
I'm trying to get the content in between square brackets within a string but my Regex isn't working.
RegExp: /\[([^\n\]]+)\]/g
It returns the correct match groups on regex101 but when I try something like '[a][b]'.match(/\[([^\n\]]+)\]/g), I get ['[a]', '[b]'] instead of ['a', 'b'].
I can get the correct results if I iterate through and do RegExp.exec, but from looking at examples online it seems like I should be able to get the match groups using String.match
You're using the String .match() method, which has different behavior from RegExp .exec() in the case of regular expressions with the "g" flag. The .match() method gives you all the complete matches across the entire searched string for "g" regular expressions.
If you change your code to
/\[([^\n\]]+)\]/g.exec('[a][b]')
you'll get the result you expect: an array in which the first entry (index 0) is the entire match, and the second and subsequent entries are the groups from the regex.
You'll have to iterate to match all of them:
var re = /\[([^\n\]]+)\]/g, search = "[a][b]", bracketed = [];
for (var m = null; m = re.exec(search); bracketed.push(m[1]));