Search code examples
javascriptjqueryregexstringtrim

Can't seem to trim all leading whitespace - JavaScript or jQuery


I'm trying to trim all leading whitespace from a textarea input box with this code:

replaceString = replaceString.replace(/^\s+|^\t+|\t+|\s+$/g, "");

When I do that, I go from

    .map_image #map_link_0 { width: 40px; height: 42px; top: 11px; left: 11px; }
    .map_image #map_link_1 { width: 47px; height: 42px; top: 62px; left: 19px; }

to

.map_image #map_link_0 { width: 40px; height: 42px; top: 11px; left: 11px; }
 .map_image #map_link_1 { width: 47px; height: 42px; top: 62px; left: 19px; }

What am I doing wrong?

JSFiddle


Solution

  • The expression by default doesn't consider multiple lines, so ^ is only matching the very beginning of your input. You can fix this by adding the multiline /m flag (for a total of /gm).

    From Mozilla's JS RE docs:

    ^ Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

    $ Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.