If $(element).text() Is In String - javascript

What I'm doing...
I would like to have a string as such:
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz";
And then check whether $(element).text() is one of the match.split("|") or simply within match.
I thought I'd be able to do if($('element').text().toLowerCase().match(/^(match)$/)) { however this wouldn't work.
Question
Why doesn't my match() work and what is my best way to resolve?

Your best way to resolve is to assign a regex to match
var match = /^(abcd|efhi|jklm|nopq|rstu|vwxyz)$/i;
Note that I added i for case insensitivity, so you can get rid of toLowerCase()
if($('element').text().match(match)) {
//...
}

My approach without using RegEx
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz".split('|');
if (match.indexOf($('element').text().toLowerCase()) !== -1) {
// match found
}

To match a variable string, you can create a Regexp object:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'g');
if($('element').text().toLowerCase().match(reg)) {}
To make it case insensitive:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'ig');
if($('element').text().match(reg)){}

Related

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

match regular expression - JavaScript

So I have the following url:
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
I want to take username and token out of it;
I tried:
var match = (/#\{(.*?)\}/g.exec(oURL));
console.log(match);
but it is giving me:
["#{username}", "username", index: 27, input: "https://graph.facebook.com/#{username}/posts?access_token=#{token}"
Why isn't catching token?
Thanks
The problem is that exec only returns the first match from the given index whenever called.
Returns
If the match succeeds, the exec() method returns an array and updates
properties of the regular expression object. The returned array has
the matched text as the first item, and then one item for each
capturing parenthesis that matched containing the text that was
captured.
If the match fails, the exec() method returns null.
You would need to loop, continuously matching again to find all the matches.
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match)
}
console.log(matches)
However, if you are only interested in the first capture group, you can only add those to the matches array:
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match[1])
}
console.log(matches)
Try this instead:
oURL.match(/#\{(.*?)\}/g)
The answer you accepted is perfect, but I thought I'd also add that it's pretty easy to create a little helper function like this:
function getMatches(str, expr) {
var matches = [];
var match;
while (match = expr.exec(str)) {
matches.push(match[1]);
}
return matches;
}
Then you can use it a little more intuitively.
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
var expr = /#\{([^\{]*)?\}/g;
var result = getMatches(oURL, expr);
console.log(result);
http://codepen.io/Chevex/pen/VLyaeG
Try this:
var match = (/#\{(.*?)\}.*?#\{(.*?)\}/g.exec(oURL));

Keeping only part of a regex match

I need to search for a word in text. For this I used this regex:
var re =/duration='\d+'/ig;
var i = text.match(re);
This gives me an array of matches like "duration='300'", "duration='400'",...
I need to get only numbers. without duration=''
You can use a capturing group:
var re = /duration='(\d+)'/ig;
var match = re.exec(text);
while (match != null) {
// matched text: match[1]
match = re.exec(text);
}
Tim's answer works well (and I'm not sure why the OP says it is not what he/she wants). That said, here is another way to do it using the String.replace() method with a callback function replacement value:
function getDurations(text) {
var re =/duration='(\d+)'/ig;
var i = [];
text.replace(re, function(m0, m1){i.push(m1); return '';});
return i;
}
Note that this technique requires no loop and is quite efficient getting the job done in a single statement.

matching values stored in variables or array with string javascript regex

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.
var patt = /apple/gi;
var newResult = patt.test(result);
I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??
To check multiple entries, you can use the OR operator:
var patt = /apple|orange/gi;
var newResult = patt.test(result);
if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):
var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);
Although in this case, you might as well use indexOf:
var key = "apple";
var newResult = result.indexOf(key) > -1;
To use a string for your regex expressions, you need to create the regex using the regex constructor.
var pattern = "apple|orange";
var regex = new RegExp(pattern, "g"); // g is for global match
Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Trouble getting my regular expression to match

I am having some trouble with my regex in javascript.
I have the following code, that I think should match, but it doesn't.
var rgx = new RegExp("{\d+:(\d+)}");
if (rgx.test("{0:00000}") == true) {
alert("match");
}
else
{
alert("no match");
}
​I am unsure if I should use test() here. I really want to catch the group, in my regex but exec() seems to give me the same result.
So what am I doing wrong?
The problem is that you need to escape the \ character in your regex:
var rgx = new RegExp("{\\d+:(\\d+)}");
Alternatively, you can use the literal syntax:
var rgx = /{\d+:(\d+)}/;
To capture the results, you should also use the .match function as opposed to test or exec. It will return null if it doesn't match and an array of at least one element if it does match.
There are multiple issues with the regex:
var rgx = new RegExp("{\d+:(\d+)}");
First (first noted by syazdani), you must string-escape the backslashes:
var rgx = new RegExp("{\\d+:(\\d+)}");
or better yet use a regex literal:
var rgx = /{\d+:(\d+)}/
Second, { and } have a special meaning in regex and should be escaped:
var rgx = /\{\d+:(\d+)\}/
Third, as noted by Ian, you might want to ensure the entire string is matched:
var rgx = /^\{\d+:(\d+)\}$/
RegExp#test returns a boolean true/false whether the string matches.
RegExp#exec returns an array holding the match and all captured groups if the string is matched, or null if the string is not matched:
var matches = /\{\d+:(\d+)\}/.exec("{0:000000}");
if(matches){
console.log(matches[1]); //logs "000000"
}

Categories