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.
Related
I'm trying to manipulate a string that has tested as a positive match against my regex statement.
My regex statement is /\[table=\d](.*?)\[\/table] / gmi and an example of a positive match would be [table=1]Cell 1[c]Cell 2[/table]. I'm searching for matches within a certain div, which I'll call .foo in the code below.
However, once the search comes back saying it has found a match, I want to have the section that was identified as a match returned back to me so that I can start manipulating a specific section of it, namely count the number of times [c] appears and reference the number in [table=1].
(function(regexCheck) {
var regex = /\[table=\d](.*?)\[\/table] / gmi;
$('.foo').each(function() {
var html = $(this).html();
var change = false;
while (regex[0].test(html)) {
change = true;
//Somehow return string?
}
});
})(jQuery);
I'm quite new to javascript and especially new to RegEx, so I apologise if this code is crude.
Thanks for all of your help in advance.
Use exec instead of test and keep the resulting match object:
var match;
while ((match = regex[0].exec(html)) != null) {
change = true;
// use `match[0]` for the full match, or `match[1]` and onward for capture groups
}
Simple example (since your snippet isn't runnable, I've just created a simple one instead):
var str = "test 1 test 2 test 3";
var regex = /test (\d)/g;
var match;
while ((match = regex.exec(str)) !== null) {
console.log("match = " + JSON.stringify(match));
}
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)){}
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));
function listPlayers(subject){
var players=[];
var myregexp = /(\S*)(?:,\s|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
players.push(match[1]);
match = myregexp.exec(subject);
}
return players;
}
The string I'm trying to match is like this �r Henderson�r�f, Pedrin�r�f, �c~�lArthur�r�f, John�r�f
The output I expect is an array like this ['Henderson�r�f', 'Pedrin�r�f', '�c~�lArthur�r�f', 'John�r�f']
What I don't understand is on regex buddy everything seems ok.
Try changing the regexp to:
var myregexp = /(\S+)(?:,\s|$)/g;
I think the loop may be because it repeatedly matches an empty string at the end.
Since I don't think you're interested in getting zero-length names, this is probably a better regexp in general.
Just for interest, a perhaps simpler way using a zero-width positive lookahead assertion:
function listPlayers( subject ) {
return subject.match( /\S+(?=,\s|$)/g );
}
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions