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 >
<input data-drupal-selector="edit-field-lorem-433" type="checkbox" id="edit-field-lorem-433" name="field_lorem[433]" value="433" >
<label for="edit-field-lorem-433">
Asie-Pacifique
</label>
</div>
I also tested with substring()
and slice()
Can you explain to me what is not working?
CodePudding user response:
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 >
<input data-drupal-selector="edit-field-lorem-433" type="checkbox" id="edit-field-lorem-433" name="field_lorem[433]" value="433" >
<label for="edit-field-lorem-433">
Asie-Pacifique
</label>
</div>