简体   繁体   中英

substring isn't working as expected on innerHtml

The string i'm working on is "innerHtml", i want to extract from it a substring starting from the index 0 until index limit .

In Javascript , the method : string.substring(startIndex, endIndex) allows to extract a substring starting with the start index and finishing with endIndex.

i Typed on my rich conteant div this: <b>B</b>

after applying substring on the innerHtml i get this: <b></b>

this is the js :

    const target = document.querySelector('#RichText')
    

    document.addEventListener('click', (event) => {
        const withinBoundaries = event.composedPath().includes(target)
       
        if (!withinBoundaries && !withinBoundaries2 && !withinBoundaries3 && !withinBoundaries4)     {
            target.innerHTML = target.innerHTML.substring(0, 3);
        }
        alert(target.innerHTML.length + target.innerHTML)
    })

what is wrong ?

For your case, You probably want to save your innterhtml to a string first then use str.replace method on your converted string.

Then you will want to substring the result, GOOD LUCK

if (!withinBoundaries && !withinBoundaries2 && !withinBoundaries3 && !withinBoundaries4) {
           var str = target.innerHTML;
           str = str.replace(/<.*>(.*)<\/.*>/g, "$1")
           var res = str.substring(0, 3);
    }

alert(res)

as @Khant said innerHTML is html, so what was missing is encode from html to string and decode from string to html:

document.addEventListener('click', (event) => {
        const withinBoundaries = event.composedPath().includes(target)
        const withinBoundaries2 = event.composedPath().includes(target2)
        const withinBoundaries3 = event.composedPath().includes(target3)
        const withinBoundaries4 = event.composedPath().includes(target4)
        
        if (!withinBoundaries && !withinBoundaries2 && !withinBoundaries3 && !withinBoundaries4) {

            var str = htmlencode(target.innerHTML);
            var innerHTML = $.parseHTML(htmldecode(str.substring(0, limit)));
            $('#RichText').html(innerHTML);
            
        }
    })
    

       
    function htmlencode(str) {

        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }
    function htmldecode(str) {

        var txt = document.createElement('textarea');
        txt.innerHTML = str;
        return txt.value;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM