Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex and jQuery to select patterns in Arabic text

This is perhaps a tricky one. Using a regex, I want to select the Arabic numbers (can be 1, 2 or 3 Arabic digits) between parentheses as well as the parentheses themselves here: http://jsfiddle.net/QL4Kr/.

<span>
    كهيعص ﴿١﴾
</span>
<span>
    وَإِلَيْهِ تُرْ‌جَعُونَ ﴿٢٤٥﴾
</span>​
jQuery(function () {    
    var oldHtml = jQuery('span').html();
    var newHtml = oldHtml.replace("","");
    jQuery('span').html(newHtml); });​
like image 670
drake035 Avatar asked Jan 18 '26 08:01

drake035


1 Answers

Here's what I came up with:

jQuery(function() {

    /* Arabic digits representation in Unicode
       See: http://stackoverflow.com/a/1676590/114029 */
    var myregex = /[\u0660-\u0669]+/;

    $('span').each(function(index) {

        var text = $(this).text();

        var matches = text.match(myregex);

        alert(index + ': ' + $(this).text());

        alert(matches);

    });

});

Here's the jsFiddle to play with it: http://jsfiddle.net/leniel/YyAXP/


Here's the modified version that keeps only the numbers inside each <span>:

jQuery(function() {

    var myregex = /[\u0660-\u0669]+/;

    $('span').each(function(index) {

        var text = $(this).text();

        $(this).text('');

        var matches = text.match(myregex);

        $(this).text(matches); 

    });

});

The jsFiddle: http://jsfiddle.net/leniel/YyAXP/1/


To correct the misunderstanding, here's a new version that does exactly what you want:

jQuery(function() {

    var myregex = /[﴾\u0660-\u0669﴿]+/;

    $('span').each(function(index) {

        var text = $(this).text();

        $(this).text('');

        var matches = text.match(myregex);

        var content = text.replace(myregex, '');

        //alert(content);
        //alert(index + ': ' + $(this).text());
        //alert(matches);

        var newSpan = document.createElement('span');

        $(newSpan).text(matches);

        $(this).text(content);

        $(newSpan).prependTo($(this));
    });
});

The corresponding jsFiddle is here: http://jsfiddle.net/leniel/YyAXP/2/


I hope this is your last requirement change! :-)

var myregex = /([\u0660-\u0669]+)/g;

var parenthesis = /[﴾﴿]+/g;

var text = $("#sentences");

//alert(content);
//var matches = $(text).text().match(myregex);
//alert(text.html());

text.html(function(i, oldHTML) {

    return oldHTML.replace(parenthesis, '').replace(myregex, '<span>$1</span>');
});

Here's the jsFiddle: http://jsfiddle.net/leniel/G4SkV/4/

like image 107
Leniel Maccaferri Avatar answered Jan 21 '26 00:01

Leniel Maccaferri