1

Can anyone tell me why my strings doesn't trim. I have this code:

firstName = $('#form-create-user #first_name').val().trim().toLowerCase();
lastName = $('#form-create-user #last_name' ).val().trim().toLowerCase();

var initials = firstName.match(/\b\w/g) || [];
initials = ((initials.shift() || '') + (initials.pop() || '')).toLowerCase();
username = initials.concat(lastName);

$('#form-create-user  #username').val(username);

I would like the username to be generated from firstname and lastname, expecting Juan De la to generate jdela.

But the output is for example:

enter image description here

4
  • 1
    .replace(/\s+/, "") should work (Regex that removes all spaces) Commented Apr 4, 2017 at 10:06
  • 1
    @deceze Why is this question off-topic? There is enough code to reproduce the problem, imo it is correct... Commented Apr 4, 2017 at 10:12
  • @Mistalis "Trim" has a specific meaning, and this code is "trimming" just fine. OP didn't specify what else they expect to happen. Commented Apr 4, 2017 at 10:26
  • 1
    @deceze The question can be better formatted. The final expecting result can be easily guessed: he wants to generated a login based on firstname/lastname. Commented Apr 4, 2017 at 10:28

2 Answers 2

1

From W3Schools:

The trim() method removes whitespace from both sides of a string.

It does not remove spaces inside a string.


You can use this regex to do the trick:

lastName = $('#form-create-user #last_name' ).val().replace(/\s/g, '').toLowerCase();

Note this regex remove all whitespaces (including tabs and new lines).

Sign up to request clarification or add additional context in comments.

Comments

0

trim will remove trailing and leading spaces not spaces between.

use

firstName = $('#form-create-user #first_name').val().trim().toLowerCase().replace(/ /g, "")

instead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.