Give priority to group inside regular expression - javascript

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/

Related

Creating new RegExp object removing one character from variable [duplicate]

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.

Javascript Replace, string with comma

I have a string that contains multiple occurrences of ],[ that I want to replace with ]#[
No matter what I try I cant get it right.
var find = '],[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
Doesn't work
mytext = mytext.replace(/],[/g,']#[');
Doesn't work
Any idea where I am going wrong?
The answer is that [ and ] are special characters in the context of regular expressions and as such need to be escaped either by means of \ i.e. to match ] you write [ when you use the convenient Javascript shorthand for regular expressions that you can find in the code below:
var regex= /\],\[/g
var result = mytext.replace(regex, ']#[')
Please check out the following jsFiddle: http://jsfiddle.net/JspRR/4/
As you can see the important bit is escaping the ] and the [ when constructing the regular expression.
Now if you did not want to use the Javascript regular expressions shorthand, you would still need to have the same escaping. However, in that case the \ character will need to be escaped itself ( ... by itself!)
var regex = new RegExp("\\],\\[", "g");
var result = mytext.replace(regex, ']#[')
The reason your example doesn't work is because normally square brackets represents a character class and therefore you need to escape them like so
var find = '\\],\\[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
You can also use a regex literal
mytext.replace(/\],\[/g, "]#[");
Try this:-
mytext.replace(/\],\[/g, ']#[')
Square brackets are special characters inside a regular expression: they are used to define a character set.
If you want to match square brackets in a regexp, you have to escape them, using back slash.
"[1],[2],[3]".replace(/\],\[/g, "]#[");
Or, in case you use the builtin constructor:
"[1],[2],[3]".replace(new RegExp("\\],\\[", "g"), "]#[");
In both case we have to use the g flag so that the regular expression can match all the occurrences of the searched string.
var str = "[1],[2],[3]";
console.log(str.replace(/\],\[/g, "]#["));
console.log(str.replace(new RegExp("\\],\\[", "g"), "]#["));
var str = "[1],[2],[3]";
var replaced = str.replace('],[', ']#[');

build Regex string with js

<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);

javascript - insert a variable into regexp

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) );

Match dynamic string using regex

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.

Categories

Resources