javascriptjqueryrtl-language

Add class by Javascript or jQuery if paragraph arabic language


I would add class when I have different language on paragraph or div like arabic language to make anther font and direction and I would make it automatic .

<div class="paragraph">
    <p>عربي لغة عربية تغير الاتجاه هنا</p>
</div>
<div class="paragraph">
    <p>example</p>
</div>

<script type="text/javascript">
    var regoo = "example|assignment";
    var re = new RegExp(regoo, 'ig');

    if($('div, p').text().match(re)) {
         $(this).addClass('gold');
    }
</script>

Solution

  • It could be done like this

    function HasArabicCharacters(text){
        var arregex = /[\u0600-\u06FF]/;
    	return arregex.test(text);
    }
    
    var textBlock = document.querySelector('#app p');
    if(HasArabicCharacters(textBlock.textContent)){
    	textBlock.classList.add('arabic');
    }
    .arabic{
    	color: green;
    }
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Arabic test</title>
    </head>
    <body>
    <div id="app">
    	<p class="text">عربي لغة عربية تغير الاتجاه هنا</p>
    </div>
    </body>
    </html>

    HasArabicCharacters function is collected from here Regular Expression For Arabic Language