문제

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