2

So I'm trying to trim any spaces BEFORE and AFTER the text input value...

Any ideas? Driving me nuts. I tried reading up on $.trim(). But can't get it to work properly.

Code:

var campaign_values = {
        name : $.trim($('.nameField').val().toLowerCase().replace(/\s/g, "_")),
        // other variables...
};
Mike Barwick
  • 6,288
  • 6
  • 51
  • 76

3 Answers3

8

Not sure what problem you were having with trim, but you should be able to use it like this:

var campaign_values = {
        name : $.trim($('.nameField').val()).toLowerCase().replace(/\s/g, "_"),
        // other variables...
};

Though in this case, I think it is clearer to use javascript trim()

var campaign_values = {
        name : $('.nameField').val().trim().toLowerCase().replace(/\s/g, "_"),
        // other variables...
};
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • First one is not working for some reason, but I got the second one to work! Thanks!! Swear I tried this... Option #2 is much cleaner! Cheers! – Mike Barwick Nov 20 '12 at 18:20
  • 1
    The first one doesn't do anything because you are first replacing all spaces(including leading and ending) with `"_"`. It should be `$.trim($('.nameField').val()).toLowerCase().replace(/\s/g, "_")` Is the native .trim() method supported in IE 6/7/8? according to MDN support started in IE9 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim – Kevin B Nov 20 '12 at 18:28
  • @KevinB Kevin, you are correct. I didn't really look at the replace call there closely when writing up my answer. I have edited to reflect this. – Mike Brant Nov 20 '12 at 18:30
4

Try using $.trim before calling replace function:

name : $.trim($('.nameField').val()).toLowerCase().replace(/\s/g, "_"),
Ram
  • 143,282
  • 16
  • 168
  • 197
0

The standard JavaScript String.trim() will remove the beginning and end whitespace from a string.

"   string  ".trim() ==  "string"
Hacknightly
  • 5,109
  • 1
  • 26
  • 27