Replacing the last word of a string in pure JS, no jQuery

Viewed 789

I'm trying to change the color of the two last word of a string.

I was trying in pure CSS, but no :last-word(s) exists, so...

I don't want to include jQuery just to do this.

<h1 id="Title">My extra super title</h1>

I tried this to get the last two. But it seems that SPLICE isn't the best option?

var h1 = document.getElementById("Title").innerHTML;
var h1 = h1.split(" ").splice(-2).join(" ");
6 Answers

var h1 = document.getElementById("Title").innerHTML;
var lastWords = h1.split(" ").splice(-2).join(" ");
var result = lastWords.trim().fontcolor("green");
const firstPrase = h1.trim().substring(0, lastWords.length - 2);
document.getElementById("Title").innerHTML = firstPrase + result
<h1 id="Title">My extra super title</h1>

You are not calling the h1 at all. Also use splice(0, 2) to get the first two characters.

Demo:

//Get el
var h1Text = document.getElementById("title")

//Get last two
var splitText1 = h1Text.textContent.split(" ").splice(-2).join(" ");

//Get first two
var splitText2 = h1Text.textContent.split(" ").splice(0, 2).join(" ");

//Replace HTML
h1Text.innerHTML = splitText2 + ' <span class="black">' + splitText1 + '</span>';
<h1 id="title">w x y z</h1>

You didn't declare id for the element.
I hope this helps:

var title = document.getElementById("Title");
var h1 = title.innerHTML;
var h2= h1.split(" ").splice(-2).join(" ");
var h3=h1.replace(h2,'');
title.innerHTML=h3

var dateSpan = document.createElement('span');
dateSpan.classList.add("red");
dateSpan.innerHTML = h2;
title.appendChild(dateSpan);
.red{
  color:red;
}
<h1 id="Title">My extra super title</h1>

I getting done. But need a lot of optimisation.

var h1 = document.getElementById("Title").innerHTML;
var originalh1 =  h1.split(" ").reverse().slice(2).reverse().join(" ");
var editedh1 = h1.split(" ").splice(-2).join(" ");
document.getElementById("Title").innerHTML = originalh1 + ' <span class="black">' + editedh1 + '</span>';

This can be achieved also with template literals and split().

let h1 = document.getElementById('Title');
let split = h1.innerText.split(' ');
let html = `<h1>${split[0]} ${split[1]} <span> ${split[2]} ${split[3]} </span></h1>`;

h1.innerHTML = html;
<h1 id="Title">My extra super title</h1>

Splice the last two words using .splice(-2), you can use a reusable function like below that also adds a highlighting class to it and append it to the renaming words. It should also work if the number of words in string changes.

function highlightText(id, className) {
  let elm = document.getElementById(id);
  let text = elm.innerText.split(" ");

  const highlight = ' <span class="' + className + '">' + text.splice(-2).join(" ") + '</span>';
  elm.innerHTML = text.join(" ") + highlight;
}

highlightText("Title", "highlight");
.highlight {
  color: #ff00ff;
}
<h1 id="Title">My extra super title</h1>

Related