简体   繁体   中英

Removing Unwanted Spaces Using javascript

In my application i want to remove the unwanted space from starting and ending.And also if there have more than space between words also remove them leaving one space. How can i do this?

Try this:

//remove leading spaces
content = content.replace(/^\s+/g,'');
//remove trailing spaces
content = content.replace(/\s+$/g,'');
//remove whitespaces in the middle
content = content.replace(/\s+/g,' ');

这应该可以删除前导和尾随空格,并将两个或多个空格减少为一个空格:

str.replace(/^\s+|\s+$/, '').replace('/\s\s+/', ' ')

You can use jQuery trim method.This function remove all new lines and all spaces leading or trailing from input string.

var str = '          it is a test string                ';

alert($.trim(str));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM