Home > Mobile >  Wrap full stop in span tag using pure JS
Wrap full stop in span tag using pure JS

Time:08-27

I have a simple string and if the last character of that string is a full stop, I want to wrap it with span tags so that I can change its colour. However, my logic doesn't seem to be working?

var title = document.querySelector(".textHero__title");
title = title.textContent.trim();
const fullstop = ".";

if( title.endsWith(fullstop) ){
  console.log("true");
  title.replace(fullstop, '<span>.</span>');
}
html{
  background: black
}

.textHero__title{
  color: red;
}

.textHero__title span{
  color: white;
}
<h1 >
  This is a title.
</h1>

CodePudding user response:

String.prototype.replace returns a new string. Strings in js are immutable.

Also, you have to call some DOM API to update the DOM.

innerHTML will be enough in this scenario

var title = document.querySelector(".textHero__title");
const titleText = title.textContent.trim();
const fullstop = ".";

if (titleText.endsWith(fullstop)) {
  console.log("true");
  const replaced = titleText.replace(fullstop, '<span>.</span>');
  title.innerHTML = replaced
}
html {
  background: black
}

.textHero__title {
  color: red;
}

.textHero__title span {
  color: white;
}
<h1 >
  This is a title.
</h1>

As Barmar said in the comment:

Another problem: replace() replaces the first match, but he wants to replace the . at the end.

In this case it doesn't matter, because you have one full stop, but if you had more, you would have to use regex with a global flag

var title = document.querySelector(".textHero__title");
const titleText = title.textContent.trim();
const fullstop = /\./g;

if (titleText.match(fullstop)) {
  console.log("true");
  const replaced = titleText.replace(fullstop, '<span>.</span>');
  title.innerHTML = replaced
}
html {
  background: black
}

.textHero__title {
  color: red;
}

.textHero__title span {
  color: white;
}
<h1 >
  This is a title. And this is a subtitle.
</h1>

  • Related