1

I have this textarea:

<textarea id="ifade" rows="6" cols="66" placeholder="...Start Writing in Arabic"></textarea>

and I have trying to do find character at both normal newline ('\n') and rendered newlines(or if I can insert the '\n' character to rendered newlines but I cannot do that also...)

var remainedPlace;
var inputValue = $("#textarea").val();
for (var j = 0; j < inputValue.length; j++) // from start of the textarea to the end of textarea ...
{
    // I cannot detect rendered newlines below..:
    for (var k = j; inputValue.charAt(k) != '\r\n' && inputValue.charAt(k) != '\r' && inputValue.charAt(k) != '\n'; k++) // from start of that line to the end of that line ...
    {
        /* doing some un-important stuff here:
        for(var l = 0; l < selections.length; l++) // from selected letters
        {
            if(inputValue.charAt(k) == selections[l]) // every selected letters
                lineSums[line]++; // increment as count in that line
            remainedPlace = k;
        }
        */
    }
    line++;
    j = ++remainedPlace;
}

I want to find out width-size dynamic line break indexes of line break characters means that when we resize textarea horizontally it should render line breaks again and so our calculated rendered new line break indexes also should change

This textarea has less 2 rendered line-breaks:<br>
<textarea rows="3" cols="66">this text will broke/render new line breaks according to textarea width even though I have never used '\n' in it character, I want to find out that rendered line break indexes created according to textarea width</textarea>

<br><br>This textarea has less 6 rendered line-breaks:<br>
<textarea rows="7" cols="23">this text will broke/render new line breaks according to textarea width even though I have never used '\n' in it character, I want to find out that rendered line break indexes created according to textarea width</textarea>

This ( Find rendered line breaks with javascript ) question seems similar but it is not working for textarea hence I have not enough points I cannot asked in comments and so I have opened this new question.

2 Answers2

0

Not 100% sure what exactly you needed as a return -- I assume it's the index of each line break. If not, comment my answer to let me know.

Details are commented in example below

// Get the text via HTMLFormElement interface
let txt = document.forms[0].elements[0].value;

// Create a RegExp object to match new lines
const rgx = new RegExp(/\n/, 'g');

/*
Run .matchAll() which returns an object
Wrap it in array brackets and apply the
...spread operator in order to access it.
Run the array through .map() and return
each match's .index value.
*/
let matches = [...txt.matchAll(rgx)];

matches = matches.map(match => match.index);

console.log(matches);
.as-console-row::after { width: 0; font-size: 0; }
.as-console-row-code { width: 100%; word-break: break-word; }
.as-console-wrapper { min-height: 100% !important; max-width: 30%; margin-left: 70%; }
<form>
  <textarea rows='10' cols='50'>
  Alan Rails, ladies and gentlemen. After his parents' tragic death in a railroad accident, he gained the power to summon ghost trains. It's not all bad though, they were spared having to see their grown son wear a whistle.
  They're not infinite universes left in sync with the show. 
  Are you hungry for apples? ARE YOU HUNGRY FOR APPLESSS!? 
  Wha, me irresponsible ?! All I wanted you to do was to hand me a screwdriver, Morty!
  </textarea>
</form>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • Yes I want size dynamic line break indexes means when we resize textarea horizontally it should render line breaks again and so rendered new line break indexes should change but this code gives same index outputs hence it is look up only for ‘\n’ character not looking for “rendered” line break indexes – Messiah Jesus Slave of RAHMAN May 06 '22 at 07:17
  • Then you'll need to continuously monitor DOM for any resizing of viewport, correct? – zer00ne May 06 '22 at 07:20
  • yes, we need to `$("#textarea_id").resize(function(){...../*detect rendered line break indexes*/.....});` But even one-time calculation is enough for me... – Messiah Jesus Slave of RAHMAN May 06 '22 at 14:00
  • *"...rendered new line break indexes should change but this code gives same index. "* My function and your function works fine -- the index is the count for each character so if the font-size was to increase, the index numbers stays the same because it's not a measurement related to size or it's position as it is in relation to it's container it's merely a place in a long line. I understand what you mean about the importance of a *"rendered:"* HTML element, *but* I think it needs a different approach. When I get back, I'l post an answer. – zer00ne May 06 '22 at 22:13
  • @AbdurRAHMANAyYıldız Are you going to extract the text from the ` – zer00ne May 07 '22 at 17:00
  • I want to count number of “specific” characters in every rendered line. This ( https://stackoverflow.com/a/55605049/2059149 ) answer near to solution but is not working for textarea – Messiah Jesus Slave of RAHMAN May 08 '22 at 09:37
  • When you mean rendered, do you mean rendered HTML? ` – zer00ne May 08 '22 at 11:02
  • read original question and run code snippet I have updated it.. – Messiah Jesus Slave of RAHMAN May 08 '22 at 16:54
  • Those *"new line breaks"* are not line breaks, those are wrapped text. Don't rely on any accuracy from `rows` and `cols` attribute values -- variations in font character widths must be considered. You should use a monospace font and a relative font-size unit for default. What will you do with these indices at `\n` and wrapped text? Have you considered `contenteditable` attribute on a block-level element? – zer00ne May 08 '22 at 19:55
  • I have considered contenteditable div but it has a lot of other issues.. I am building this: http://muqattacounter.github.io – Messiah Jesus Slave of RAHMAN May 08 '22 at 20:16
  • If you resize ` – zer00ne May 08 '22 at 20:30
0

I have fixed my problem with copying textarea value to new position fixed div then calculate rendered line-breaks in that div and much more (return rendered every line as a string in an array of strings) like this with some help of other Stack Overflow reply.

But their approach is not good for texts which has both right to left and left to right content like I have in MuqattaCounter.github.io so I have changed it little bit and now it looks from up to bottom in order to find new rendered lines and doesn't affect from rtl or ltr texts, it can handle both of them together.

In order to see true console.log results first click "Run code snippet" and then click "make it full page" and then resize the page

$(window).resize(function(){
    console.log(getLineBreaks(document.querySelector('.copiedText')));
});


function getLineBreaks(elem) {
    // our Range object form which we'll get the characters positions
    const range = document.createRange();
    // here we'll store all our lines
    const lines = [];
    const nodes = grabTextNodes(elem);
    let bottom = 0;
    // initial position
    let prevBottom = null;
    let lineText = "";
    let startRange = null;
    for (const node of nodes) {
        let nodeText = node.textContent;
        const textLength = nodeText.length;
        let rangeIndex = 0;
        let textIndex = 0;
        while (rangeIndex <= textLength) {
            range.setStart(node, rangeIndex);
            if (rangeIndex < textLength - 1) {
                range.setEnd(node, rangeIndex + 1); // wrap the range (for Chrome...)
            }
            bottom = range.getBoundingClientRect().bottom;
            if (prevBottom === null) { // first pass
                prevBottom = bottom;
                startRange = range.cloneRange();
            }
            else if (bottom > prevBottom) { // line break
                // store the current line content
                lineText += nodeText.slice(0, textIndex);
                startRange.setEnd(range.endContainer, range.endOffset);
                const { bottom } = startRange.getBoundingClientRect();
                lines.push(lineText);
                // start a new line
                prevBottom = bottom;
                lineText = "";
                nodeText = nodeText.slice(textIndex);
                textIndex = 0;
                startRange = range.cloneRange();
            }
            rangeIndex++;
            textIndex++;
            prevBottom = bottom;
        }
        // add the remaining text from this node into the current line content
        lineText += nodeText;
    }
    // push the last line
    startRange.setEnd(range.endContainer, range.endOffset);
    //const { bottom } = startRange.getBoundingClientRect();
    lines.push(lineText);
  
    return lines;
}

function grabTextNodes(elem) {
    const walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null);
    const nodes = [];
    while (walker.nextNode()) {
        nodes.push(walker.currentNode);
    }
    return nodes;
}
#copyText{
    display:inline-block;
    width: 361 px !important;
    white-space: pre-wrap !important;
    word-wrap: break-word !important;
    position: fixed;
    overflow: hidden !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="copyText" class="copiedText">13:0 بسم الله الرحمن الرحيم
13:1 المر تلك ءايت الكتب والذى أنزل إليك من ربك الحق ولكن أكثر الناس لا يؤمنون
13:2 الله الذى رفع السموت بغير عمد ترونها ثم استوى على العرش وسخر الشمس والقمر كل يجرى لأجل مسمى يدبر الأمر يفصل الءايت لعلكم بلقاء ربكم توقنون
13:3 وهو الذى مد الأرض وجعل فيها روسى وأنهرا ومن كل الثمرت جعل فيها زوجين اثنين يغشى اليل النهار إن فى ذلك لءايت لقوم يتفكرون
13:4 وفى الأرض قطع متجورت وجنت من أعنب وزرع ونخيل صنون وغير صنون يسقى بماء واحد ونفضل بعضها على بعض فى الأكل إن فى ذلك لءايت لقوم يعقلون
13:5 وإن تعجب فعجب قولهم أءذا كنا تربا أءنا لفى خلق جديد أولئك الذين كفروا بربهم وأولئك الأغلل فى أعنقهم وأولئك أصحب النار هم فيها خلدون
13:6 ويستعجلونك بالسيئة قبل الحسنة وقد خلت من قبلهم المثلت وإن ربك لذو مغفرة للناس على ظلمهم وإن ربك لشديد العقاب
13:7 ويقول الذين كفروا لولا أنزل عليه ءاية من ربه إنما أنت منذر ولكل قوم هاد
13:8 الله يعلم ما تحمل كل أنثى وما تغيض الأرحام وما تزداد وكل شىء عنده بمقدار
13:9 علم الغيب والشهدة الكبير المتعال
13:10 سواء منكم من أسر القول ومن جهر به ومن هو مستخف باليل وسارب بالنهار
13:11 له معقبت من بين يديه ومن خلفه يحفظونه من أمر الله إن الله لا يغير ما بقوم حتى يغيروا ما بأنفسهم وإذا أراد الله بقوم سوءا فلا مرد له وما لهم من دونه من وال
13:12 هو الذى يريكم البرق خوفا وطمعا وينشئ السحاب الثقال
13:13 ويسبح الرعد بحمده والملئكة من خيفته ويرسل الصوعق فيصيب بها من يشاء وهم يجدلون فى الله وهو شديد المحال
13:14 له دعوة الحق والذين يدعون من دونه لا يستجيبون لهم بشىء إلا كبسط كفيه إلى الماء ليبلغ فاه وما هو ببلغه وما دعؤا الكفرين إلا فى ضلل
13:15 ولله يسجد من فى السموت والأرض طوعا وكرها وظللهم بالغدو والءاصال
13:16 قل من رب السموت والأرض قل الله قل أفاتخذتم من دونه أولياء لا يملكون لأنفسهم نفعا ولا ضرا قل هل يستوى الأعمى والبصير أم هل تستوى الظلمت والنور أم جعلوا لله شركاء خلقوا كخلقه فتشبه الخلق عليهم قل الله خلق كل شىء وهو واحد القهر
13:17 أنزل من السماء ماء فسالت أودية بقدرها فاحتمل السيل زبدا رابيا ومما يوقدون عليه فى النار ابتغاء حلية أو متع زبد مثله كذلك يضرب الله الحق والبطل فأما الزبد فيذهب جفاء وأما ما ينفع الناس فيمكث فى الأرض كذلك يضرب الله الأمثل
13:18 للذين استجابوا لربهم الحسنى والذين لم يستجيبوا له لو أن لهم ما فى الأرض جميعا ومثله معه لافتدوا به أولئك لهم سوء الحساب ومأوىهم جهنم وبئس المهاد
13:19 أفمن يعلم أنما أنزل إليك من ربك الحق كمن هو أعمى إنما يتذكر أولوا الألبب
13:20 الذين يوفون بعهد الله ولا ينقضون الميثق
13:21 والذين يصلون ما أمر الله به أن يوصل ويخشون ربهم ويخافون سوء الحساب
13:22 والذين صبروا ابتغاء وجه ربهم وأقاموا الصلوة وأنفقوا مما رزقنهم سرا وعلانية ويدرءون بالحسنة السيئة أولئك لهم عقبى الدار
13:23 جنت عدن يدخلونها ومن صلح من ءابائهم وأزوجهم وذريتهم والملئكة يدخلون عليهم من كل باب
13:24 سلم عليكم بما صبرتم فنعم عقبى الدار
13:25 والذين ينقضون عهد الله من بعد ميثقه ويقطعون ما أمر الله به أن يوصل ويفسدون فى الأرض أولئك لهم اللعنة ولهم سوء الدار
13:26 الله يبسط الرزق لمن يشاء ويقدر وفرحوا بالحيوة الدنيا وما الحيوة الدنيا فى الءاخرة إلا متع
13:27 ويقول الذين كفروا لولا أنزل عليه ءاية من ربه قل إن الله يضل من يشاء ويهدى إليه من أناب
13:28 الذين ءامنوا وتطمئن قلوبهم بذكر الله ألا بذكر الله تطمئن القلوب
13:29 الذين ءامنوا وعملوا الصلحت طوبى لهم وحسن مءاب
13:30 كذلك أرسلنك فى أمة قد خلت من قبلها أمم لتتلوا عليهم الذى أوحينا إليك وهم يكفرون بالرحمن قل هو ربى لا إله إلا هو عليه توكلت وإليه متاب
13:31 ولو أن قرءانا سيرت به الجبال أو قطعت به الأرض أو كلم به الموتى بل لله الأمر جميعا أفلم يايءس الذين ءامنوا أن لو يشاء الله لهدى الناس جميعا ولا يزال الذين كفروا تصيبهم بما صنعوا قارعة أو تحل قريبا من دارهم حتى يأتى وعد الله إن الله لا يخلف الميعاد
13:32 ولقد استهزئ برسل من قبلك فأمليت للذين كفروا ثم أخذتهم فكيف كان عقاب
13:33 أفمن هو قائم على كل نفس بما كسبت وجعلوا لله شركاء قل سموهم أم تنبءونه بما لا يعلم فى الأرض أم بظهر من القول بل زين للذين كفروا مكرهم وصدوا عن السبيل ومن يضلل الله فما له من هاد
13:34 لهم عذاب فى الحيوة الدنيا ولعذاب الءاخرة أشق وما لهم من الله من واق
13:35 مثل الجنة التى وعد المتقون تجرى من تحتها الأنهر أكلها دائم وظلها تلك عقبى الذين اتقوا وعقبى الكفرين النار
13:36 والذين ءاتينهم الكتب يفرحون بما أنزل إليك ومن الأحزاب من ينكر بعضه قل إنما أمرت أن أعبد الله ولا أشرك به إليه أدعوا وإليه مءاب
13:37 وكذلك أنزلنه حكما عربيا ولئن اتبعت أهواءهم بعد ما جاءك من العلم ما لك من الله من ولى ولا واق
13:38 ولقد أرسلنا رسلا من قبلك وجعلنا لهم أزوجا وذرية وما كان لرسول أن يأتى بءاية إلا بإذن الله لكل أجل كتاب
13:39 يمحوا الله ما يشاء ويثبت وعنده أم الكتب
13:40 وإن ما نرينك بعض الذى نعدهم أو نتوفينك فإنما عليك البلغ وعلينا الحساب
13:41 أولم يروا أنا نأتى الأرض ننقصها من أطرافها والله يحكم لا معقب لحكمه وهو سريع الحساب
13:42 وقد مكر الذين من قبلهم فلله المكر جميعا يعلم ما تكسب كل نفس وسيعلم الكفر لمن عقبى الدار
13:43 ويقول الذين كفروا لست مرسلا قل كفى بالله شهيدا بينى وبينكم ومن عنده علم الكتب
</div>
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Given that 99% of the code here is taken from one of my answers, a link to said answer would be fair. Also beware, I also did start with top vs bottom but this will fail if your text contains various font-size. So for your case (a – Kaiido May 09 '22 at 09:22
  • As per my other note: I can't speak for moderators, but I am fairly sure you would be looking at a suspension if you keep adding off-topic material to your posts. To save you from that eventuality, I have rolled this back to the last good version. – halfer Feb 25 '23 at 19:23