Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrap full stop in span tag using pure JS

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 class="textHero__title">
  This is a title.
</h1>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="textHero__title">
  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 class="textHero__title">
  This is a title. And this is a subtitle.
</h1>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading