I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"
var searchStr = 'width';
var strRegExPattern = '/'+searchStr+'\b/';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
Please don't put '/' when you pass string in RegExp option
Following would be fine
var strRegExPattern = '\\b'+searchStr+'\\b';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:
var regex = /width\b/g;
If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:
var regex = new RegExp('width\\b', 'g');
The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.
The right tool for this job is not regex, but String.indexOf:
var str = '32:width: 900px;',
search = 'width',
isInString = !(str.indexOf(search) == -1);
// isInString will be a boolean. true in this case
Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf
Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.
Also consider escaping metacharacters in the string if you intend them to only match their literal values.
var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
You can use back tick symbol to make your string dynamic "`".
var colName = 'Col1';
var result = strTest.match(`xxxxxxx${colName}`);
by injecting ${colName} in to the text, it can be editable dynamically.
Related
I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"
var searchStr = 'width';
var strRegExPattern = '/'+searchStr+'\b/';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
Please don't put '/' when you pass string in RegExp option
Following would be fine
var strRegExPattern = '\\b'+searchStr+'\\b';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:
var regex = /width\b/g;
If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:
var regex = new RegExp('width\\b', 'g');
The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.
The right tool for this job is not regex, but String.indexOf:
var str = '32:width: 900px;',
search = 'width',
isInString = !(str.indexOf(search) == -1);
// isInString will be a boolean. true in this case
Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf
Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.
Also consider escaping metacharacters in the string if you intend them to only match their literal values.
var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
You can use back tick symbol to make your string dynamic "`".
var colName = 'Col1';
var result = strTest.match(`xxxxxxx${colName}`);
by injecting ${colName} in to the text, it can be editable dynamically.
This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You should use double slash:
var regex = new RegExp("\\?", "g");
Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"
And "\\?", becomes "\?"
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
A must-read: RegExp: Description at MDN.
I want my output to be what's inside var data = "THIS";, to do so I've manage to do this:
var plaintext = fs.readFileSync( process.argv[ 1 ] ).toString();
var regex = new RegExp("var\\ data\\ =\\ \"(.{0,})\";", "g", "y");
var regex2 = new RegExp("\"(.{0,})\"", "g");
var info = JSON.parse(plaintext.match(regex)[0].match(regex2)[0]);
Is there any way to have only one regular expression, and compact the code into 2 or 3 lines?
How about this?
plaintext.match(/var\s+data\s*=\s*"(.*)";/)[1]
Update: This regex will also match strings that contain escaped quotes, e.g. "\"foo\"" as long as these quotes aren't followed by a semicolon. For this to work, the closing quote must be immediately followed by a semicolon.
As an alternative, you could also exclude double quotes from the matched string (Use [^"]* instead of .*) and leave out the semicolon from the regular expression.
Here is my approach:
var matches = plaintext.match(/var data = "([^"]+)"/);
https://jsfiddle.net/7hy8epp5/
<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,''));
</script>
And it works fine - return all the digits in the string.
However when I put quote marks around the regex like this:
var regex = "/[^\d]/g"; This doesn't work.
How can I turn a string to a working regex in this case?
Thanks
You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)
Here is the literal way:
var regex = /[^\d]/g;
In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.
Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.
Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.
var regex = new RegExp("[^\\d]", "g");
Hope this makes sense.
As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:
var regex = "[^\\d]";
Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp.
So overall:
var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);
I have the following which works fine, allowing a form field to be valid if blank or containing the word "hello" or passing the other validation...
var re = new RegExp(/^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/);
but I want to make the word "hello" be the value of a variable.
I have tried this but it no longer seems to work:
var i = "hello";
var re = new RegExp('/^$|^['+i+']|^([FG]?\d{5}|\d{5}[AB])$/');
There are several things wrong in your code.
RegExp expects a string, not a regex literal like you pass in the first case. It seems that RegExp is smart enough though and detects that you are passing a regex literal. So your first example works by coincidence and is the same as:
var re = /^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/;
The / are not part of the expression, they are the delimiters to denote a regex literal, much like quotation marks (') indicate a string literal. Hence, if you pass the expression as string to RegExp, it should not contain /.
Since the backslash is the escape character in strings as well, in order to create a literal backslash for the expression you have to escape it: \\.
[hello] does not test for for the word hello, it matches either h, e, l or o, thus it is equivalent to [ehlo].
With all that said, your code should be:
var i = "hello";
var re = new RegExp('^$|^'+i+'|^([FG]?\\d{5}|\\d{5}[AB])$');
Drop the leading and trailing / characters and your reg exp is not going what you expect. Double up the \ characters so they are escaped. Also [] means match any of these characters.
Basic example
var str = "hello world";
var word = "hello"
var re = new RegExp("^" + word + "\\s?")
console.log( str.match(re) );