Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

charAt don't work with jquery text() on label but works with simple string

I’m trying to get the first character of a fetched string with jQuery text(). It works if I test with a simple hard-coded string:

var str = 'hello';
var first_char = str.charAt(0);
console.log('first_char : ' + first_char);

But I can’t do it with the text of a label retrieved with text()

var str = $('.form-item-field-lorem-433 label').text();
console.log('str : ' + str);
var first_character = str.charAt(0);
console.log('first_character : ' + first_character);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-item-field-lorem-433">
  <input data-drupal-selector="edit-field-lorem-433" type="checkbox" id="edit-field-lorem-433" name="field_lorem[433]" value="433" class="form-checkbox form-check-input">
  <label class="form-check-label" for="edit-field-lorem-433">
        Asie-Pacifique
      </label>
</div>

I also tested with substring() and slice()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can you explain to me what is not working?

>Solution :

The issue is because the string from text() also contains the whitespace from the HTML. You can use trim() to remove this:

var str = $('.form-item-field-lorem-433 label').text().trim(); // trim here
console.log('str : ' + str);

var first_character = str.charAt(0);
console.log('first_character : ' + first_character);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-item-field-lorem-433">
  <input data-drupal-selector="edit-field-lorem-433" type="checkbox" id="edit-field-lorem-433" name="field_lorem[433]" value="433" class="form-checkbox form-check-input">
  <label class="form-check-label" for="edit-field-lorem-433">
    Asie-Pacifique
  </label>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading