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
Related
How to get all text following the symbol ":"?
I have tried:
'prop:bool*'.match(/:(.[a-z0-9]+)/ig)
But it returns [":bool"] not ["bool"].
Update:
I need to use this inside the following expression:
'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
["prop", "bool", "*"]
You could solve this by performing a positive lookbehind action.
'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\*/ig)
The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':'.
The result should here be ["prop", "bool", "*"].
Edit:
Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following:
'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)
This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:
var str = 'prop:bool*';
var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length);
console.log(match);
When the match is successful, an array of one element will hold the value :bool. That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool.
var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\*)/ig);
console.log(a,b.substring(1,b.length),c);
To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b.
You could simply do:
'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]
If your entire string is of the form you show, you could just use a regex with capture groups to get each piece:
console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\*)/i).slice(1));
This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I have this Example 1:
myString = 'cdn.google.com/something.png';
console.log(myString.match(myString));
Everything works just fine, but when it comes to Example 2:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(myString));
It returns the value of 'null'. I don't know what happened anymore.. I searched for the keywords 'a string does not Match itself' and found nothing. Can somebody help me? Thank you.
The String#match method would treat the argument as a regex(by parsing if not), where . and ? has special meaning.
. matches any character (except for line terminators)
? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed
So . wouldn't cause any problem since . can be used to match any character except line but ? would since it's using to match zero or one-time occurrence of any character.
For eg: .png?23 => matches .png23 or .pn23
From MDN docs :
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
It's better to use String#indexOf instead which returns the index in the string if found or returns -1 if not found.
console.log(myString.indexOf(myString) > -1);
match in Javascript compares a String against a RegEx. Luckily in your first example it works.
I guess you are looking for a method like localCompare.
Hope this helps!
match() search the string using a regular expression pattern.
So
var s = "My String";
s.match(/Regex Here/);
will try to match s for given regular expression .
In your example:-
myString = 'cdn.google.com/something.png'; // It will be treated as regex
console.log(myString.match(myString));
myString = 'cdn.google.com/something.png?231564'; // It will be treated as regex , result differ because of ?
console.log(myString.match(myString));
You can escape the argument to match, however if you do that you could just use == to compare the strings. This post contains a regex string escape function:
How to escape regular expression in javascript?
RegExp.quote = function(str) {
return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It can be used like this:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(RegExp.quote
(myString)));
If you want to match any number after the question mark, you could do it like this:
myString = 'cdn.google.com/something.png?';
console.log((myString+"18193819").match(RegExp.quote
(myString) + '\\d+'));
From the MDN the split method separator is treated as a String or a RegExp. But 'asd'.split(['s']) correctly returns ['a', 'd'].
The specification for split includes the following step:
Let R be ToString(separator).
So the array is coerced to a string, and the string representation of ['s'] is s.
It's worth noting that if you pass a regex to split, it doesn't get this far, as the regex object has an internal ##split method, which is used in step 3:
If separator is neither undefined nor null, then
a. Let splitter be GetMethod(separator, ##split).
b. ReturnIfAbrupt(splitter).
c. If splitter is not undefined , then
i. Return Call(splitter, separator, «O, limit»).
I am trying to write a function that builds a regular expression that can test whether a string starts with a string and contains another string.
function buildRegExp(startsWith,contains){
return new RegExp( ????? )
}
for example:
buildRegExp('abc','fg').test('abcdefg')
The above expression should evaluate to true, since the string 'abcdefg' starts with 'abc' and contains 'fg'.
The 'startsWith', and the 'contains' strings may overlap eachother, so the regular expression cannot simply search for the 'startsWith' string, then search for 'contains' string
the following should also evaluate to true:
buildRegExp('abc','bcd').test('abcdefg')
I cannot use simple string functions. It needs to be a regular expression because I am passing this regular expression to a MongoDB query.
A pattern like this would handle cases where the startsWith / contains substrings overlap in the matched string:
/(?=.*bcd)^abc/
i.e.
return new RegExp("(?=.*" + contains + ")^" + startsWith);
Try this regexp
(^X).*Y
E.g. in javascript
/(^ab).*bc/.test('abc') => false
/(^ab).*bc/.test('abcbc') => true
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.