سؤال

I need to remove all the white spaces before the first character (which is not a white space) and remove all the white spaces after the last character (which is not a white space).

Looks like this:

'                 a boat has an anchor       '

Should be 'a boat has an anchor'

'   $$%&@$&$%& lollerskates #372734§     '

Should be '$$%&@$&$%& lollerskates #372734§'

Please ignore the single quotes, they are there to show the white space.

هل كانت مفيدة؟

المحلول

string.replace(/^\s+|\s+$/g, "");

نصائح أخرى

There is a native method for this. string.trim

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

var orig = "   foo  ";

alert( orig.trim() );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top