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
Related
I have a string like aman/gupta and I want to replace it to aman$$gupta and for that I am using JavaScript replace method as follows:
let a = "aman/gupta"
a = a.replace("/", "$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$$")
console.log(a) // 'aman$$gupta'
Why are the 1st and 2nd case identical and I get the expected result when I use $$$ instead of $$?
It’s because $$ inserts a literal "$".
So, you need to use:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
See the following special patterns:
Pattern
Inserts
$$
Inserts a "$".
$&
Inserts the matched substring.
$`
Inserts the portion of the string that precedes the matched substring.
$'
Inserts the portion of the string that follows the matched substring.
$n
Where n is a non-negative integer less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object.
$<Name>
Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., "$<Name>").
Also you can use split and join for better performance and $ isn't special for those functions.
var a = "aman/gupta"
a = a.split('/').join('$$')
alert(a); // "aman$$gupta"
To avoid the need to escape special characters you can use anonymous function as a replacer
a = "aman/gupta";
a = a.replace("/", function() {return "$$"});
console.log(a); // "aman$$gupta"
String.prototype.replace() documentation
Specifying a function as a parameter
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
The replace method provides replacement patterns that start with a dollar sign. One of them is $$ which inserts a single $. A single dollar sign in the replacement string will result in a literal one.
So if you want clean literal dollar signs, use $$ replacement patterns accordingly:
console.log('aman/gupta'.replace('/','$$')); // aman$gupta
console.log('aman/gupta'.replace('/','$$$$')); // aman$$gupta
console.log('aman/gupta'.replace('/','$$$$$$')); // aman$$$gupta
In regular expression replace with groups, if replacement is a variable, it needs to dollar sign escaped. Otherwise there will be bugs.
function escapeDollarSign(str) {
return str.replace(/\$/g, "$$$$")
}
Use below code its working for me.
var dollar = "$$$$";
console.log('abhishe/kadam'.replace('/', dollar.replace(new RegExp('\\$', '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
Let's say I have this regexp
(^|;)[\s]*style=([^;]*)
And a string to match against
test=en; style=night
According to the MDN documentation for String.match
I can pass in a regexp literal - /(^|;)[\s]*style=([^;]*)/
I can pass a string, which is wrapped in a RegExp object - "(^|;)[\s]*style=([^;]*)"
Or I can pass in a RegExp object created - new RegExp("(^|;)[\s]*style=([^;]*)")
The problem is that they do not all evaluate to the same value.
/(^|;)[\s]*style=([^;]*)/ => array of matches
"(^|;)[\s]*style=([^;]*)" => null
new RegExp("(^|;)[\s]*style=([^;]*)") => null
What is going on in this case? Why don't they all evaluate to the same set of matches?
BTW. Tested on Chrome 38.0.2125.101 and IE 11.0.9600.17278
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
hidValue="javaScript:java";
replaceStr = "java";
resultStr=hidValue.replace("/\b"+replaceStr+"\b/gi","");
resultStr still contains "javaScript:java"
The above code is not replacing the exact string java. But when I change the code and directly pass the value 'java' it's getting replaced correctly i.e
hidValue="javaScript:java";
resultStr=hidValue.replace(/\bjava\b/gi,"");
resultStr contains "javaScript:"
So how should I pass a variable to replace function such that only the exact match is replaced.
The replace-function does not take a string as first argument but a RegExp-object. You may not mix those two up. To create a RexExp-object out of a combined string, use the appropriate constructor:
resultStr=hidValue.replace(new RegExp("\\b"+replaceStr+"\\b","gi"),"");
Note the double backslashes: You want a backslash in your Regular Expression, but a backslash also serves as escape character in the string, so you'll have to double it.
Notice that in one case you're passing a regular expression literal /\bjava\b/gi, and in the other you're passing a string "/\bjava\b/gi". When using a string as the pattern, String.replace will look for that string, it will not treat the pattern as a regular expression.
If you need to make a regular expression using variables, do it like so:
new RegExp("\\b" + replaceStr + "\\b", "gi")
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
`let msisdn = '5093240556699'
let isdnWith = numb.msisdn.slice(8,11);
let msisdnNew = msisdn.replace(isdnWith, 'XXX', 'gi');
show 5093240556XXX`
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.