Count regular expression matches in jQuery - javascript

I need to count a group of regular expressions in a dynamically loaded <div> that I've loaded using the load() function. I also need to resize this <div> to the longest line of characters in it. Is there a way to achieve this? I've tried searching around and can't find anything, not even on SO. I should mention that the expression I am testing for is:
Sat Mar 12 12:45:38 PST 2011
Using this regex:
if ($('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/))

var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi; //noticed the g. g will enable match of all occurance, and without it it'll only match the first occurance
console.log(str.match(patt1).length); //4 matched
JavaScript match regex function returns an array so you can basically do a length on that array and get the size of the matched elements. Make sure you are using the g in RegEx to search all occurance
Based on your RegEx you can do the following:
$('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/g).length //this should give you the total count of occurance

kjy112 gave you your answer. Like that answer clarified, this isn't really jQuery, but Javascript RegEx's (so maybe that was throwing off your search).
If that regex turns out to be slow-- which it might if you return many dates-- you can just count some nique component, such as just the years:
$('#result').text().match(/\d{4}/).length

Malfy,
3 ways to get the width of a string come to mind. I'll go over those first, then how to get the length of the longest. It looks like others have addressed the regex.
1) (fastest)
If only the text itself needs to be a certain width, not the div, then you can use white-space:nowrap to ensure the text remains the full width.
$('div.someClass').css('whiteSpace','nowrap');
2) (slowest)
If you need the pixel width of a string to set another div's width, one way to do that is to create an element containing that string and use the css property above. Example:
var yourString = 'your string';
// create a div containing your string
var $tempDiv = jQuery('<div style="visibility:hidden;position:absolute;white-space:nowrap">'+jQuery.trim(yourString)+'</div>').appendTo('body');
$newDiv = <your new div, however you're creating it>;
// set the width of the new div to the width of the temp div
$newDiv.width($tempDiv.width());
// and clean up;
$tempDiv.remove();
//repeat as necessary
3) (quite fast too)
Alternately, if you're sure you'll be using a monospace font (courier, consolas, etc). There's a much faster way. Save the width of a single character and multiplying it by the length of each new text string. That way you aren't writing a new element each time. For example:
var $tempDiv = $('<div style="visibility:hidden;margin:0;padding:0;border:0;">z</div>').appendTo('body');
//(any character will work. z is just for example);
var reusableCharacterWidth=$tempDiv.width();
$tempDiv.remove();
var firstString = your string';
// set the width of your first div
$newDiv.width(reusableCharacterWidth*firstString.length);
var nextString = 'your next string';
// set the width of your next div
$nextNewDiv.width(reusableCharacterWidth*nextString.length);
(note: you may want to use $.trim() on the strings just in case)
To get the longest string:
var longestLineLength,
yourText= 'your text here';
function getLongestLineLength(lines){
var oneLineLength,
longest=0,
linesArray = lines.split('\n');
for(var i=0,len=linesArray.length;i<len;i++){
oneLineLength=linesArray[i].length;
longest=oneLineLength>longest?oneLineLength:longest;
}
return longest;
}
longestLineLength = getLongestLineLength(yourText);
Cheers!
Adam

Related

Get id from url

I have the following example url: #/reports/12/expense/11.
I need to get the id just after the reports -> 12. What I am asking here is the most suitable way to do this. I can search for reports in the url and get the content just after that ... but what if in some moment I decide to change the url, I will have to change my algorythm.
What do You think is the best way here. Some code examples will be also very helpfull.
It's hard to write code that is future-proof since it's hard to predict the crazy things we might do in the future!
However, if we assume that the id will always be the string of consecutive digits in the URL then you could simply look for that:
function getReportId(url) {
var match = url.match(/\d+/);
return (match) ? Number(match[0]) : null;
}
getReportId('#/reports/12/expense/11'); // => 12
getReportId('/some/new/url/report/12'); // => 12
You should use a regular expression to find the number inside the string. Passing the regular expression to the string's .match() method will return an array containing the matches based on the regular expression. In this case, the item of the returned array that you're interested in will be at the index of 1, assuming that the number will always be after reports/:
var text = "#/reports/12/expense/11";
var id = text.match(/reports\/(\d+)/);
alert(id[1]);
\d+ here means that you're looking for at least one number followed by zero to an infinite amount of numbers.
var text = "#/reports/12/expense/11";
var id = text.match("#/[a-zA-Z]*/([0-9]*)/[a-zA-Z]*/")
console.log(id[1])
Regex explanation:
#/ matches the characters #/ literally
[a-zA-Z]* - matches a word
/ matches the character / literally
1st Capturing group - ([0-9]*) - this matches a number.
[a-zA-Z]* - matches a word
/ matches the character / literally
Regular expressions can be tricky (add expensive). So usually if you can efficiently do the same thing without them you should. Looking at your URL format you would probably want to put at least a few constraints on it otherwise the problem will be very complex. For instance, you probably want to assume the value will always appear directly after the key so in your sample report=12 and expense=11, but report and expense could be switched (ex. expense/11/report/12) and you would get the same result.
I would just use string split:
var parts = url.split("/");
for(var i = 0; i < parts.length; i++) {
if(parts[i] === "report"){
this.reportValue = parts[i+1];
i+=2;
}
if(parts[i] === "expense"){
this.expenseValue = parts[i+1];
i+=2;
}
}
So this way your key/value parts can appear anywhere in the array
Note: you will also want to check that i+1 is in the range of the parts array. But that would just make this sample code ugly and it is pretty easy to add in. Depending on what values you are expecting (or not expecting) you might also want to check that values are numbers using isNaN

Replace some of a matched string in javascript

I'm working on a grid layout function. I'm about 1/2 way there and have hit a wall.
I am using a string and running a single RegExp function per box I'm placing in the grid to determine where it will fit (based on number of rows/columns it occupies). This works successfully. Demonstration:
function findSpace(columns, rows){
var totalColumns = 4;
var grid = "11002100020000200002";
//1 represents occupied space, 0 empty space, and 2 a new line
var reg = RegExp("(0{" + columns + "})(([0-2]{" + (totalColumns - columns + 1) + "})0{"+columns+"}){" + (rows-1) + "}");
var i = grid.search(reg);
return i.index;
}
Returns the index of the match, letting me know where in my grid this box will fall. See fiddle.
I fall short trying to replace the "0"s with "1"s. Doing grid.replace(reg, "1") of course replaces everything from the beginning of the match to the end with a single "1". I need to replace just the "0"s that will be occupied for row and column, each with a "1", and not any of the characters matched between.
This is an exercise in doing things differently. Yes, I could do this with an array data structure. What fun is that? I'm not looking for a "don't do it this way do it the way everyone else does" answer, I'm trying to determine the most efficient way to solve my scenario.
Thanks!
The String#replace method might be the ticket. If you pass a regular expression and a function as the second parameter, you can dynamically manipulate each match.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Regular Expression on Javascript

I have snippet javascript (web) but since i try to use RegExpression it should work almost the same.
I have a string with some coordinates in it seperated by a space charakter (last coordinate has no space after it).
var coords = "0:0 0:0:0 1:0:1 0:0:0:1 0:0:1 0:0:2";
var part = "0:0";
I want to have all the coordinates beginning with the value of part ("0:0") plus ":" and the next coordinate number. If a coordinate matches but has more than one additional "coordinate-dimensions" it shouldn't show...
For example it should show 0:0:0, 0:0:1 and 0:0:2 but NOT 0:0 (because to less dimension), 0:0:0:1 (because if the additional dimension)
What I tryed is something like:
var reg = new RegExp("(^|\\s)(0:0:\\d\\s)", "g");
alert(coords .match(reg));
But it seems not to work propperly.
Anyone has an idea?!
Kind regards!
You can use this regex:
"(?:^|\\s)(0:0:\\d)(?=\\s|$)"

JavaScript - How to get at specific value in a string?

I have a string from which I am trying to get a specif value. The value is buried in the middle of the string. For example, the string looks like this:
Content1Save
The value I want to extract is "1";
Currently, I use the built-in substring function to get to remove the left part of the string, like this:
MyString = "Content1Save";
Position = MyString;
Position = Position.substring(7);
alert(Position); // alerts "1Save"
I need to get rid of the "Save" part and be left with the 1;
How do I do that?
+++++++++++++++++++++++++++++++++++++++++
ANSWER
Position = Position.substr(7, 1);
QUESTION
What's the difference between these two?
Position = Position.substr(7, 1);
Position = Position.substring(7, 1);
You can use the substr[MDN] method. The following example gets the 1 character long substring starting at index 7.
Position = Position.substr(7, 1);
Or, you can use a regex.
Position = /\d+/.exec(Position)[0];
I would suggest looking into regex, and groups.
Regex is built essentially exactly for this purpose and is built in to javascript.
Regex for something like Content1Save would look like this:
rg = /^[A-Za-z]*([0-9]+)[A-Za-z]*$/
Then you can extract the group using:
match = rg.exec('Content1Save');
alert(match[1]);
More on regex can be found here: http://en.wikipedia.org/wiki/Regular_expression
It highly depends on the rules you have for that middle part. If it's just a character, you can use Position = Position.substring(0, 1). If you're trying to get the number, as long as you have removed the letters before it, you can use parseInt.
alert(parseInt("123abc")); //123
alert(parseInt("foo123bar")); //NaN
If you're actually trying to search, you'll more often than not need to use something called Regular Expressions. They're the best search syntax JavaScript avails.
var matches = Position.match(/\d+/)
alert(matches[0])
Otherwise you can use a series of substr's, but that implies you know what is in the string to begin with:
MyString.substr(MyString.indexOf(1), 1);
But that is a tad annoying.

regular expression (javascript) How to match anything beween two tags any number of times

I'm trying to find all occurrences of items in HTML page that are in between <nobr> and </nobr> tags.
EDIT:(nobr is an example. I need to find content between random strings, not always tags)
I tried this
var match = /<nobr>(.*?)<\/nobr>/img.exec(document.documentElement.innerHTML);
alert (match);
But it gives only one occurrence. + it appears twice, once with the <nobr></nobr> tags and once without them. I need only the version without the tags.
you need to do it in a loop
var match, re = /<nobr>(.*?)<\/nobr>/img;
while((match = re.exec(document.documentElement.innerHTML)) !== null){
alert(match[1]);
}
use the DOM
var nobrs = document.getElementsByTagName("nobr")
and you can then loop through all nobrs and extract the innerHTML or apply any other action on them.
(Since I can't comment on Rafael's correct answer...)
exec is doing what it is supposed to do - finding the first match, returning the result in the match object, and setting you up for the next exec call. The match object contains (at index 0) the whole of the string matched by the whole of the regex. In subsequent slots are the bits of the string matched by the parenthesized subgroups. So match[1] contains the bit of the string matched by "(.*?)" in your example.
you can use
while (match = /<nobr>(.*?)<\/nobr>/img.exec("foo <nobr> hello </nobr> bar <nobr> world </nobr> foobar"))
alert (match[1]);
If the strings you're using aren't xml elements, and you're sticking with regexes the return value you're getting can be explained by the bracketing. .exec returns the whole matching string followed by the contents of the bracketed expressions.
If your doc contains:
This is out.
Bzz. This is in. unBzz.
then
/Bzz.(.*?)unBzz./img.exec(document.documentElement.innerHTML)
Will give you 'Bzz. This is in. unBzz.' in element 0 of the returned array and 'This is in.' in element 1. Trying to display the whole array gives both as a comma separated list because that's what JavaScript does to try to display it.
So
alert($match[1]);
is what you're after.
it takes to steps but you could do it like this
match = document.documentElement.innerHTML.match(/<nobr>(.*?)<\/nobr>/img)
alert(match)//includes '<nobr>'
match_length = match.length;
for (var i = 0; i < match_length; i++)
{
var match2 = match[i].match(/<nobr>(.*?)<\/nobr>/im);//same regex without the g option
alert(match2[1]);
}

Categories