Bit of an odd one:
I’m making an input element that displays suggested results, and highlights the input value as a substring of each result.
So for example if I typed ‘cat’ it would suggest and highlight category
I’m just adding a strong tag to the result: content.innerHTML = ${arr[x].substr(0, index)}<strong>${arr[x].substr(index, match.length)}</strong>${arr[x].substr(index+match.length)};
Stripped down codepen example here
My problem – which I can’t seem to replicate in the codepen above despite it being the same innerHTML code – is that if the match is next to a space, that space disappears. Eg: ‘tes’ => ‘This is atest’.
The space is in the html (below), and the string outputs correctly to the console, so I feel like this has to be down to the strong tag?
No doubt I’ll kick myself when someone points out my mistake, but I just can’t see it
>Solution :
In the screenshot of the dev tools I can see that the containing div is a flexbox, where the codepen it is not. It is the flexbox that is causing this.
See snippet below
const content = document.querySelectorAll(".content");
const arr = ["Red square", "Blue circle", "Green rectangle"];
const match = "rec";
content.forEach((element) => {
for (let x = 0; x < arr.length; x++) {
if (arr[x].toUpperCase().indexOf(match.toUpperCase()) !== -1) {
const index = arr[x].toUpperCase().indexOf(match.toUpperCase());
element.innerHTML = `${arr[x].substr(0, index)}<strong>${arr[x].substr(
index,
match.length
)}</strong>${arr[x].substr(index + match.length)}`;
}
}
});
.wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
background-color: lightgrey;
}
.content {
height: 10rem;
width: 20rem;
font-size: 1.7rem;
background-color: white;
margin-bottom: 1rem;
}
.withFlex {
display: flex;
}
<div class="wrapper">
<div>No Flexbox</div>
<div class="content"></div>
<div>With Flexbox</div>
<div class="content withFlex"></div>
</div>
