0

In my application, I have a autocomplete list of names that gets populated when the user types in my textbox. This list is populated by an array being returned by an api call and looks like this in the debugger/DOM:

<ul className="suggestions">
    <li>John  Brown</li>
    <li>Mary  Waters</li>
    ...
</ul>

Notice that there are 2 spaces between the first and last name. This might be because the data being returned is "dirty" or perhaps its by design. Lets assume though, that I want to keep those 2 spaces. My problem is that when the user clicks on of the items, it triggers my event handler which looks like this:

onClick = e => {
    this.setState({
        activeSuggestion: 0,
        filteredSuggestions: [],
        showSuggestions: false,
        userInput: e.currentTarget.innerText
    });
};

When I check the value of e.currentTarget.innerText it now shows "John Brown" with only a single space. I don't have any slice, splice, replace, etc... methods to parse this string to remove it so my question then is "Does .innerText" remove the 2nd space automatically? If so, is there a way to keep the 2nd space when grabbing the userInput selected by the user?"

gwydion93
  • 1,681
  • 3
  • 28
  • 59
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText – Kevin B Jun 17 '21 at 14:26
  • 1
    Does this help? https://stackoverflow.com/questions/47768523/empty-spaces-are-ignored-by-the-innertext-property It's not that innertext is removing anything or ignoring anything, it's giving you the *rendered* version of the html. textContent or innerHTML would be better at getting you a more accurate representation of the data, however even those can be modified by the browser. The DOM shouldn't be used to store data. – Kevin B Jun 17 '21 at 14:38
  • In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space ` ` – Uchiha Itachi Jun 17 '21 at 14:44
  • Just for the record, the 1st comment perfectly explains and answers my question. – gwydion93 Jun 17 '21 at 17:43

2 Answers2

1

As mentioned in the comments, developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText perfectly explains whats going on here. To resolve this issue, I changed

userInput: e.currentTarget.innerText

to

userInput: e.currentTarget.innerHtml

This retains the extra space in the 'dirty' data.

gwydion93
  • 1,681
  • 3
  • 28
  • 59
-1

If having two spaces is important, take a look at using html non-breaking space...

&nbsp;

I suspect that the pre-processor is removing the extra space the way it would for say extra newlines...