How can I encase a portion of text within a span using JavaScript?

I have the following HTML structure:

<p>one two three four</p>

I would like to modify it using JavaScript so that it appears as:

<p>one <span>two three</span> four</p>

I already have the starting position and the length for the text I want to enclose in a span: for example, start = 4 and len = 9. If jQuery could simplify this process, I am open to using it.

To wrap a portion of text within a <span> using JavaScript, you can use either plain JavaScript or jQuery. Here’s how you can accomplish it in both ways:

Using Plain JavaScript:

let paragraph = document.querySelector('p');
let text = paragraph.textContent;

// Define start and length
let start = 4, len = 9;

// Extract parts of the text
let before = text.slice(0, start);
let target = text.slice(start, start + len);
let after = text.slice(start + len);

// Create the new HTML structure
paragraph.innerHTML = `${before}<span>${target}</span>${after}`;

Using jQuery:

$('p').each(function() {
  let text = $(this).text();
  let start = 4, len = 9;

  let before = text.slice(0, start);
  let target = text.slice(start, start + len);
  let after = text.slice(start + len);

  // Update the paragraph
  $(this).html(`${before}<span>${target}</span>${after}`);
});

Both methods are efficient, but jQuery can simplify DOM manipulation if you are already using it in your project. By dynamically updating the innerHTML or using .html() with jQuery, you encase the desired text efficiently.