jQuery: parsing a text file with shortcodes

In this post I will show you how to parse a text file containing shortcodes with jQuery. The technique detailed here, which makes use of the $.ajax() method and regular expressions, can be applied to INI files as well.

Our text file has the following structure:

[header level="1"]Titolo[/header]
[para]Testo[/para]

We have to create an helper function which splits the file into lines using the \n character and then use regular expression to match and filter the shortcodes. Finally, it returns an array containing the corresponding HTML elements:

function parseText(text) {

	var parts = text.split(/\n/);
	var header = /^\[header\s.+\].+\[\/header\]$/;
	var para = /^\[para\].+\[\/para\]$/;
	var matches = [], i, len = parts.length;
	
	for(i = 0; i < len; i += 1) {
	
		var part = parts[i];
		
		if(header.test(part)) {
		
			var heading = '', level = /level="\d"/, headerText = /\].+\[/;
			
			var levelNumberMatch = part.match(level);
			var levelNumber = levelNumberMatch[0].replace(/level="+/g, '').replace('"', '');
			
			heading += '<h' + levelNumber + '>';
			
			var levelTextMatch = part.match(headerText);
			var levelText = levelTextMatch[0].replace('[', '').replace(']', '');
			
			heading += levelText + '</h' + levelNumber + '>';
			
			matches.push(heading);
			
		
		}
		
		if(para.test(part)) {
		
		
			var paragraph = '';
			var paraMatch = part.match(para);
			var paragraphText = paraMatch[0].replace(/\[\/?para]/g, '');
			
			paragraph = '<p>' + paragraphText + '</p>';
		
			matches.push(paragraph);
		
		}
		
	
	
	
	}
	
	
	return matches;



}

Now we can use the $.ajax() method by specifying the dataType option as text and turning the returned array of strings into a single HTML string by using join():

$(function() {

	$.ajax({
		type: 'GET',
		dataType: 'text',
		url: 'test.txt',
		success: function(text) {
		
			var textParts = parseText(text);
			
			$('#test').html(textParts.join(''));
		
		}
    });

});

You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.