How can I automatically move last single letters to a new line on my website?

Hi,

I`m creating a website and was asked to move the last single letters to the new line. I thought it can be done with &nbsp but it would take a lot of time to edit whole website conent by hand. I found an interesting article&text=Oczywiście%20robimy%20to%20za%20pomocą,literę%20z%20poprzedzającym%20go%20wyrazem.) with some kind of solution:

function lastSingleLetterToNewLine(el){ let result; el.forEach((element, i)=>{ if(!element.innerHTML.match(/[{}]|<script|^\n$/gi)){ result = element.innerHTML.replace(/ (.) /gi, " “+‘$1’+”&nbsp ;"); } element.innerHTML = result; console.log(result); }); } let el = document.querySelectorAll(“h1, h2, h3, h4, h5, p, span, .text”); lastSingleLetterToNewLine(el);

I have no coding knowleadge but manged to create js that automatically moves last single letters to new line. Most of the work has been done by ChatGPT. The cool part is that this works dynamically - so it doesn`t matter what size is the screen of our page visitor.

I think it might helpful for some people so here is my tutorial:

1. Create a new js file:

Edit code-> Assets → Create new

I named it “lastSingleLetterToNewLine.js”

2. Insert the code:

function lastSingleLetterToNewLine(el) { el.forEach((element, i) => { if (!element.innerHTML.match(/[{}]|<script|^\n$/gi)) { let result = element.innerHTML.replace(/ ([aiouwz]) /gi, " " + ‘$1’ + “&nbsp”); element.innerHTML = result; console.log(result); } });}document.addEventListener(“DOMContentLoaded”, function () { let el = document.querySelectorAll(“h1, h2, h3, h4, h5, p, span, text, liquid, Body, Subtitle, rte subtitle, div”); lastSingleLetterToNewLine(el);});

3. Insert the code referance into pages you want to modify

{{ ‘lastSingleLetterToNewLine.js’ | asset_url | script_tag }}

f.e. you want to modify the page where image-with-text.liquid is visible simply insert it at the top of the page

MKSCshop_2-1703069379962.png

this also works with pages of products f.e. mian-product.liquid

Enjoy!

  • it should work for all types of text on the pages but if doesnt work for you... Heres what you can do:

1. Inspect the text you want the code to work with:

F12 then click on this inspect button (top left corrner)

2. Check which part of the code is the element you want to modify

MKSCshop_1-1703069150151.png

in this example I`ve added div and rte subtitle (again I have no coding knowleadge but it works)

3. Add this extension to this list:
(“h1, h2, h3, h4, h5, p, span, text, liquid, Body, Subtitle, rte subtitle, div”);

and save the " lastSingleLetterToNewLine.js" file