Javascript regexp does not work - javascript

Test string is "page-42440233_45778105"
pattern "(page-\d+_\d+)"
Online tester(http://www.regexr.com/) successfuly finded mathc,but in browser js result is null. Why?
var re = new RegExp("(page-\d+_\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);

I think this would be a better pattern
var re = /^page-\d+_\d+$/i;
It also matches the beginning (^) and end ($) of the string
message.match(re);
//=> ["page-42440233_45778105"]

You need to escape \ if you use string literal:
var message = "page-42440233_45778105";
var re = new RegExp("(page-\\d+_\\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
// => ["page-42440233_45778105"]
More preferably, use regular expression literal:
var re = /(page-\d+_\d+)/gim;

When you use a string literal, you must escape the \ :
var re = new RegExp("(page-\\d+_\\d+)", "gim");
A better solution here would be to use a regex literal :
var re = /(page-\d+_\d+)/gim
Don't use the RegExp constructor if the regular expression is constant, regex literals are much more convenient.

Related

JavaScript regex: replace variables of whole string in a sentence [duplicate]

How to create regex pattern which is concatenate with variable, something like this:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Thanks
var re = new RegExp("/\b"+test+"\b/");
\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the // in this context.)
With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53'
const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags
console.log('51, 52, 53, 54'.match(regexp))
you can use
/(^|,)52(,|$)/.test('51,52,53')
but i suggest to use
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )

Shouldn't this RegExp work?

testString = "something://something/task?type=Checkin";
patt = new RegExp("something\/(\w*)\?");
match = patt.exec(testString);
document.querySelector('#resultRegexp').innerHTML = match[1];
I want to capture task So shouldn't this RegExp work?
I am grabbing any alphanumeric character up until the question mark... and capturing it.
http://jsfiddle.net/h4yhc/2/
You would need to escape the slash in regex literals, and the backslash in string literals which you create regexes from:
var patt = /something\/(\w*)\?/g;
// or
var patt = new RegExp("something/(\\w*)\\?", 'g');
I strongly recommend the first version, it is more readable.
I think this would be enough: (\w*)\?, since / is not captured by \w and the only ? in the string is after your target string.
This is what you need:
patt = new RegExp(".*/(\\w*)\\?");
http://jsfiddle.net/FJcfd/
try with this: var pat = /something:\/\/(?:[^\/]+\/)+(\w+)\?(\w+=\w+)/;
it can match string such as:
something://something/task?type=Checkin
something://something/foo/task?type=Checkin
something://something/foo/bar/task1?type3=Checkin4

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

Convert a string variable to regular expression in java script?

so I am trying to search a string for a sub string, and apparently, I must use regular expressions with the .search function, this is the code I have
var str = items[i].toLowerCase;
var str2 = document.getElementById("input").value.toLowerCase;
var index = str.search(str2);
Obhiously this doesn't work and I get an error, saying str.search is not a function, how would I go about changing these two strings into regular expressions?
thanks
Use this:
new RegExp("your regex here", "modifiers");
Take a look into:
Using a string variable as regular expression
add braces to your function calls:
var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();
var index = str.search(str2);
otherwise type of "str" is a function, not result of function execution
your problem is forgetting a set of brackets () -- and as such str and str2 get assigned a function rather than the result of calling that function! Simply change the code:
var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();
var index = str.search(str2);
To use an expression in a RegExp constructor:
var re = new RegExp(str, 'g');
will create a regular expression to match the value of str in a string, so:
var str = 'foo';
var re = new RegExp(str, 'i');
is equivalent to the RegExp literal:
var re = /foo/i;
You can use any expression that evaluates to a valid regular expression, so to match foo at the start of a string:
var re = new RegExp('^' + str, 'i');
The only niggle is that quoted characters must be double quoted, so to match whitespace at the end of a string:
var re = new RegExp('\\s+$');
which is equivalent to:
var re = /\s+$/;

JavaScript regex pattern concatenate with variable

How to create regex pattern which is concatenate with variable, something like this:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Thanks
var re = new RegExp("/\b"+test+"\b/");
\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the // in this context.)
With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53'
const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags
console.log('51, 52, 53, 54'.match(regexp))
you can use
/(^|,)52(,|$)/.test('51,52,53')
but i suggest to use
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )

Categories

Resources