Create regex object using string input [duplicate] - javascript

This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 4 years ago.
I have a regex when I instantiate the Regex object like this:
this.checkRegex = new RegExp(/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/);
It works fine, however If I store the regex in string it does not work:
private checkReg: string = '/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/';
this.checkRegex = new RegExp(this.checkReg);
I am using angular-typescript. What is the thing I am missing here when I am trying to instantiate by throwing string inside the constructor. Code sample will be really appreciated. Thanks for your help.

When you are passing a string to the RegExp constructor, you need to change it a little bit. Instead of
'/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/'
You would omit the preceding and trailing slash
'^([0|\\[+][0-9]{0,5})?([1-9][0-9]{0,15})$'
Note also double escaping the back slash.

If you want to store the RegExp as a String, store it without the forward slashes at the front and back. When creating the RegExp object, those get escaped:
new RegExp('/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/');
will result in
/\/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$\//
while,
new RegExp('^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$');
will work:
/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$/

Related

Pattern check returning false javascript/typescript [duplicate]

This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 6 years ago.
I am trying to validate if a string I entered matches the date format 'MM/yyyy'
Below is a sample of the code I am using for the same:
var date='05/2016'
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$');
patt.test(date);
However the above code is returning false.
I tried running it with the regex checker:
https://regex101.com/
The pattern seems to be working fine.
Could someone please let me know what is missing.
https://jsfiddle.net/ymj6o8La/
You have to escape the string that is passed to RegExp (the backslashes).
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
Even better, in your case, it's not dynamic, so you should use the literal RegExp instead
var patt = /^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$/
You should escape your backslashes. To represent \d or even \ you should another backslash behind it (e.g: \\) :
var date = '05/2016'
var patt = new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
console.log(patt.test(date));
Try using a pattern like this
patt= /^((0[1-9])|(1[0-2]))\/(\d{4})$/;

RegEx: Extract GET variable from URL [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.

Removing any character besides 0-9 + - / * and ^ [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

Javascript replace() function [duplicate]

This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
This is a simple replace() question - and I can't get it working to replace a substring in the function below.
function linkOnClick(){
var anyNameYouLike = 'some sort of text/string right here';
anyNameYouLike.replace('right','in');
alert(anyNameYouLike)
}
It should return "some sort of text/string in here" but doesn't. What am I doing wrong? I'm fairly new with Javascript (if it isn't obvious...)
anyNameYouLike = anyNameYouLike.replace('right','in');
In javascript, strings are immutable (they are never modified). As such, the .replace() function does not modify the string you call it on. Instead, it returns a new string. So, if you want anyNameYouLike to contain the modified string, you have to assign the result to it like this:
anyNameYouLike = anyNameYouLike.replace('right','in');
For more info, refer to the MDN description of the .replace() method which says this:
Returns a new string with some or all matches of a pattern replaced by
a replacement. The pattern can be a string or a RegExp, and the
replacement can be a string or a function to be called for each match.
And, in the description of the .replace() method, it says this:
This method does not change the String object it is called on. It
simply returns a new string.

javascript replace query string value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
add or update query string parameter
I am trying to replace the page number in the query string no matter what digit is to 1.
query string
index.php?list&page=2&sort=epub
javascript
window.location.href.replace(new RegExp("/page=.*?&/"), "page=1&")
Your code looks almost right; however:
you need to use either new RegExp or the special // regex syntax, but not both.
the replace method doesn't modify the string in-place, it merely returns a modified copy.
rather than .*?, I think it makes more sense to write \d+; more-precise regexes are generally less likely to go awry in cases you haven't thought of.
So, putting it together:
window.location.href = window.location.href.replace(/page=\d+/, "page=1");

Categories