简体   繁体   中英

Split text and wrap it in the span element

I am trying to take the sentence inside the tag that looks like this:

<p>Hello world. Lorem ipsum lorem.</p>

And transform it in this via JS/jQuery:

<p><span>Hello world.</span> Lorem ipsum lorem.</p>

Only thing that comes to my mind is the wrapAll() method, but how could I be sure that I can select the correct text - so the first part including the dot (Hello world.) ?

You can do it with a simple JS script:

let el = document.querySelect('...')
let str = el.innerText;
let indx = str.indexOf('.',0) + 1;
el.innerText = "<span>${str.substr(0,indx)}</span>${str.substr(indx)}"

You should be more specific: what exactly do you want to wrap in span? The part of the paragraph to the first period?

If so, you you have to check the index of the first period:

const ParagraphHTML = $('p#yourParagraph').html();
const PeriodIndex = ParagraphHTML.indexOf('.');

Then, you can slice your string into two parts, and join them with span:

const String1 = ParagraphHTML.slice(0,PeriodIndex+1);
const String2 = ParagraphHTML.slice(PeriodIndex+1);
const ResultString = `<span>${String1}</span>${String2}`;
$('p#yourParagraph').html(ResultString);

I used jQuery, as you mentioned in the post. More variables than needed, are used for better readbility.

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