jedu
jedu

Reputation: 1341

Replacing space with   causes invisble â character

I am populating a select box with a list of options like this:

optionsString = optionsString.replace(/\s/g, ' ');

I am doing this to preserve the spaces between the words. I do not want the DOM to remove additional spaces if I have words like:

<option>a b    c</option>

If I console log the value of the select box I get:

a b c instead of a b c which is exactly what I want. However, there is a hidden character â that gets added after b.

When I sent the string to the backend database, the database was not able to find any record belonging to a b c. When I converted the string to hexadecimal I saw the invisible character. Is there a way to not remove space without adding this special character?

Upvotes: 3

Views: 1350

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074425

Note that &nbsp; creates a non-breaking space, not just a space. If you're using the value of the option, it will have non-breaking spaces in it, not just spaces. If you want them to be spaces, you have to replace them with spaces:

const value = theSelectBoxOrOptionElement.value.replace(/\u00A0/g, " ");

(\u00A0 is the non-breaking space character that &nbsp; creates.)

Note, though, that \s will match any whitespace, not just a space, so your replace is a lossy operation (all kinds of whitespace are replaced with &nbsp;, so we can't know which were which when we want to go back).

Here's an example:

let optionsString = `a b    c`;
optionsString = optionsString.replace(/\s/g, "&nbsp;");

document.body.insertAdjacentHTML(
    `beforeend`,
    `<select id="the-select">
        <option>${optionsString}</option>
    </select>`
);

const select = document.getElementById(`the-select`);
const rawValue = select.value;
console.log(`rawValue:`, codePoints(rawValue));
const updated = rawValue.replace(/\u00A0/g, " ");
console.log(`updated:`, codePoints(updated));

function codePoints(value) {
    return [...value].map(v => v.codePointAt(0).toString(16).padStart(2, "0")).join(" ");
}

Upvotes: 6

Related Questions