Reputation: 3
I have written a javascript code that process a batch of text into chunks of 100 characters, and does Regex-text match (i.e 5 Oranges 6 Apples 20 Pears matches in text) separately.
I like the regex-match script will automatically run against each chunk (per 100 characters) and output the match results in sequence, preferably formatted inside a table.
The problem: 1) Regex-match function doesn't run on the new chunks each time the string is cut into 100 characters 2) I'm struggling to loop the regex-match function
Your help is much appreciated.
var str = " Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas....";
var chunks = [];
var chunkSize = 100;
while (str) {
if (str.length < chunkSize) {
chunks.push(str);
break;
} else {
chunks.push(str.substr(0, chunkSize) + total() + "<p></p>");
/// I tried to run the regex match function in this line for each new chunk of 100 characters but failed
str = str.substr(chunkSize);
}
}
function getMatches(string, regex, index) {
index || (index = 1);
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
function total() {
var myString = str;/// I'm trying to pick up each new chunks (100 characters)
var myString;
var myRegEx_apple = /(?:^|\s)apple(.*?)(?:\s|$)/g;
var matches = getMatches(myString, myRegEx_apple, 1);
document.getElementById("myRegEx_apple").innerHTML = (matches.length + ' apple matches found' + '\n');
var myRegEx_pears = /(?:^|\s)pears(.*?)(?:\s|$)/g;
var matches = getMatches(myString, myRegEx_pears, 1);
document.getElementById("myRegEx_pears").innerHTML = (matches.length + ' pears matches found' + '\n');
Upvotes: 0
Views: 366
Reputation: 167
It seems like you didn't try to solve your problem stepwise.
You should try to get valid chunks and verify it before going to the next step.(I couldn't make out where you do this correctly in your code, sorry if I missed something).
Iterate through each items of the chunks array and match the string with each 3 terms ("Apple","Pears", "Bananas").
Try using this function to chop your string in 100 character chunks:
function chop(str){
return str.match(/.{1,100}/g);
}
with
chunks=chop(str);
you should get an array of 100-char strings. From there you go to step 2. Make sure you use the 'g' flag (global flag) in/after your regex.
Upvotes: 1