简体   繁体   中英

Break word at specific character

I realise that similar questions have been asked, but none quite like this.

I have a situation where I am using BEM to display some classes in code tags. Below is an example:

在此处输入图片说明

Obviously the default behaviour is to break words at a hyphen, as we can see is happening in the example. Is there a way that I can control what characters the line-break occurs at? I would like to be able to have class name integrity maintained so that the line break occurs before each period . if necessary.

Unfortunately I don't think there is a way to do everything you want with pure CSS.

UPDATE: removed spaces before periods in JS solution.

If you are able to use JavaScript you could process the code tag's contents to disable wrapping for words with hyphens and you could wrap each block starting with a period in an inline-block span.

The following code breaks the contents of each code tag into a list of blocks that start with either space or period. Each block is wrapped with a span that prevents wrapping, and blocks that begin with a period are additionally marked as display: inline-block; . This should give the behaviour you are looking for, and additionally preserve all content when copy-pasting text.

CSS:

.no-wrap-hyphen {
    white-space: nowrap;
}
.wrap-period {
    display: inline-block;
}

JavaScript (run this function on window load and resize):

function wrapPeriodsNotHyphens() { // run on window load or resize
    var codes = document.getElementsByTagName( "code" );

    for ( var i = 0; i < codes.length; i++ ) {

        currentCode = codes[ i ].innerHTML.split(/(?=[ .])/); // split by spaces and periods

        for ( var c = 0; c < currentCode.length; c++ ) {
            // surround each item with nowrap span
            currentCode[ c ] = '<span class="no-wrap-hyphen">' + currentCode[ c ] + '</span>';
            if ( currentCode[ c ].indexOf( '.' ) > -1 ) {
                // add a zero size space at the start for periods
                currentCode[ c ] = '<span class="wrap-period">' + currentCode[ c ] + '</span>';
            }
        }

        codes[ i ].innerHTML = currentCode.join('');
    }
}

I have another solution using jquery,

 $('.mypara').each(function () { var str = $(this).html(); var htmlfoo = str.split('.').join('</br>'); $(this).html(htmlfoo); });
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <code class="mypara"> This is-the HTML if its - characters exceed 50. characters it should go-to next line </code> <code class="mypara"> This is the HTM-if its. characters exceed 50 - characters it should. go-to next-line </code>

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