'JavaScript or jQuery to select the last x letters in a string

html:

<select id="dropdown">

<optgroup>
<option>11111</option>
<option>22222</option>
</optgroup>

<optgroup>
<option>33333</option>
<option>44444</option>
</optgroup>

</select>

I want to select the last 4 characters of the string in every <option>, then style them as color:white;. But I still need them to be there, just that no one can see.

This is what I have:

let myStr = document.querySelector('#dropdown optgroup  option').innerHTML;
let lastChar = myStr[myStr.length -4];

it only selects the second character in the string, maybe a for loop to select all last 4?



Solution 1:[1]

You could use the slice method to select the last x characters in a string.

let myStr = document.querySelector('#dropdown optgroup option').innerHTML;
let lastChar = myStr.slice(-4);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

Solution 2:[2]

Expanding on what one of the comments said:

<select id="dropdown">

  <optgroup>
    <option value="11111">1</option>
    <option value="22222">2</option>
  </optgroup>

  <optgroup>
    <option value="33333">3</option>
    <option value="44444">4</option>
  </optgroup>

</select>

Styling won't work anyway (you have very limited options styling select elements), and even if it did, making the colour the same as the background is extremely bad practice. If you must do that sort of thing in the future it's best to manipulate the element itself rather than try to hide it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BitSteven
Solution 2 harryburk