Using variable in a regex - javascript

say i have the following variables:
myId; //Email_PDF
currentHoverOnItem; //Email_PDF_english of Email_PDF_Dutch or ...
So the first value is "Email_PDF" and the second is "Email_PDF_english". What i want i when currentHoverOnItem contains myId, then something can be executed.
This is what i have so far:
var pattern = new RegExp("^/"+myId+"/$");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Is this the right way to use the regex? It should match part of the string, there can be text before or after the match.

Is this the right way to use the regex?
No! Regexes are for patterns, not for literal strings. Use indexOf
if (currentHoverOnItem.indexOf(myId) >= 0)
{
//Do something
}

Try this
var pattern = new RegExp(myId, "g");
if (currentHoverOnItem.match(pattern))
{
//Do something
}

Your pattern is "anchored", meaning that ^ and $ specifiy begin and end of your string.
To match "Email_PDF_english" in an anchored pattern you could use
^Email_PDF_(.*)$, but it won't match if your string is longer, as your comment suggests.
If it's not anchored you could test for a blank following the Email_PDF_... string, ie
Email_PDF_([^\s]*)\s+

You need not use a reg_exp here. Using indexOf will do the trick for you
if(currentHoverOnItem.indexOf(myId) != -1)
{
//Do something
}

Related

Java Script Regex Is not working as expected [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

javascript : problem with regular expression

I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);

Javascript match one regex, but not another

How can I find all words in string which
match one expression:
/[a-zA-Z]{4,}/
but do not match another one:
/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/
Something like pseudocode:
string.match( (first_expression) && ( ! second_expression) )
You could just do this:
string.match(/[a-zA-Z]{4,}/) && !string.match(/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/)
But if you'd like to combine the patterns, you can use a negative lookahead ((?!...)), like this:
string.match(/^(?!.*\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b).*[a-zA-Z]{4,}.*$/)
But this will reject the whole string if it finds the second pattern—e.g."fooz barz" will return null.
To ensure the words you find do not match the other pattern, try this:
string.match(/\b(?![a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b)[a-zA-Z]{4,}\b/)
In this case, "fooz barz" will return "barz".
Note that this can be cleaned up a bit by using the case insensitive flag (i):
string.match(/\b(?![a-z]([a-z])\1+[a-z]\b)[a-z]{4,}\b/i)
if(string.match(first_expression))
{
if(!string.match(second_expression))
{
//Do something important
}
}
This should match what you want and not what you don't.

Javascript Regex not passing test string

I am using javascript regex to test a string. It should fail the text string but somehow its passing it. Any clue, what is wrong with this code?
<script>
var format = "^[a-zA-Z\.\-' ]*[a-zA-Z]+[a-zA-Z\.\-' ]*";
var testingValue = "FN306716";
var regex = new RegExp(format);
if (regex.test(testingValue) == false) {
alert('validation failed');
}
else {
alert('validation passed');
}
</script>
Just guessing that you are missing $ at the end of your regex to test full string.
var regex = /^[a-zA-Z\.\-' ]*[a-zA-Z]+[a-zA-Z\.\-' ]$/;
With this regex, your input wouldn't pass, because it contains numbers.
EDIT: I have updated it to use regex literal as pointed out in comments.
You're missing $ (end of input anchor):
Regex should be:
var format = "^[a-zA-Z.' -]*[a-zA-Z]+[a-zA-Z.' -]*$";
Also remember that - need not be escaped when used at fist and last position in character class and dot . also need not be escaped inside character class.
Live Demo: http://www.rubular.com/r/Q26cgQVJTm

How do I use regex to perform a validation?

I'd like to evaluate a form field using a regex.
What expression do I use to actually compare the value to the regex?
I'm imagining something thus:
if($('#someID').val() == /someregex/) {doSomething()}
But that doesn't work. Any advice?
Use
if (/^someregex$/.test($('someID').value()) {
// match
} else {
// no match
}
Note that there is no value() method in jQuery, you need to use val() and match like this:
if($('#someID').val().match(/someregex/) {
// success
}
More Info:
http://www.regular-expressions.info/javascript.html
use the match method of the strings..
string.match(regexp)
so in your case
if( $('#someID').value().match(/someregex/) ) {doSomething()}
I think you're looking for .test():
var myRegex = /someregex/;
if ( myRegex.test($('#someID').value()) ) {
doSomething();
}
You can use exec() to check it and get an array of it's matches, or match() from the string object.
We don't compare values to regular expressions. We use regular expressions to test if a value matches a pattern.
Something like:
if (/myRegExp/.test($('#myID').val()) {
//... do whatever
}
see
http://www.evolt.org/regexp_in_javascript

Categories