This is probably a silly question, but I am not overly familiar with this so I have been racking my brain trying to figure it out.
I have this set of code that I have compiled which in a nutshell, allows me to take a piece of text from a page and apply it as a title tag elsewhere, by adding a simple attribute (titletag).
Everything works perfectly, but where I have hit a roadblock is if the beforeInput and afterInput attributes are not set, then 'undefined' is added before/after the main input for the title tag. I have included some HTML so you can see what I mean.
EDIT: Added this piece to it, is this the best approach for tackling this?
const arr = [beforeInput, titleInput, afterInput];
const titleVal = arr.filter((elem) => elem !== undefined);
<script>
$(document).ready(function (){
let beforeInput = $("[titletag=input]").attr("titletag-before"); // Text Going Before The Main Input
let titleInput = $("[titletag=input]").text(); // Main Input for The Title Tag
let afterInput = $("[titletag=input]").attr("titletag-after"); // Text Going After The Main Input
// Bring Everything Together and Apply The Title Tag Where TitleTag = Output Is Set
$("[titletag=output]").attr('title', beforeInput + ' ' + titleInput + ' ' + afterInput);
// If TitleTag-RemoveInput = True, Then Remove from Page
$("[titletag-removeinput=true]").remove();
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function (){
let beforeInput = $("[titletag=input]").attr("titletag-before"); // Text Going Before The Main Input
let titleInput = $("[titletag=input]").text(); // Main Input for The Title Tag
let afterInput = $("[titletag=input]").attr("titletag-after"); // Text Going After The Main Input
// Bring Everything Together and Apply The Title Tag Where TitleTag = Output Is Set
$("[titletag=output]").attr('title', beforeInput + ' ' + titleInput + ' ' + afterInput);
// If TitleTag-RemoveInput = True, Then Remove from Page
$("[titletag-removeinput=true]").remove();
});
</script>
</head>
<body>
<h1>Add Any Text To Title Tag</h1>
<p titletag="input" titletag-removeinput="true">Add This To Title Tag</p>
<p titletag="output">Add The Title Tag Here</p>
</body>
</html>