Home > OS >  JavaScript or jQuery to select the last x letters in a string
JavaScript or jQuery to select the last x letters in a string

Time:05-12

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?

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Firstly, you don't need jQuery, and in your example, there is no trace of it. Secondly, check https://www.w3schools.com/js/js_string_methods.asp in your case myStr.substr(-4) or something like that... Note document.querySelector() will only return the first found elemet that matches the criteria. To get all of them you should use document.querySelectorAll instead but that will give you an array of found objects.

  • Related