最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Remove all space on input text using javascript - Stack Overflow

programmeradmin1浏览0评论

here is my html:

<input class="form" type="text" placeholder="test" />

and my JS

var str = $(".form").val();
var newStr = str.replace(/\s+/g, '');

there is no space when user input text. How to I create the javascript? anybody help? Thank you

here is my html:

<input class="form" type="text" placeholder="test" />

and my JS

var str = $(".form").val();
var newStr = str.replace(/\s+/g, '');

there is no space when user input text. How to I create the javascript? anybody help? Thank you

Share Improve this question edited Jul 5, 2017 at 3:15 dedi wibisono asked Jul 5, 2017 at 3:08 dedi wibisonodedi wibisono 5335 gold badges12 silver badges23 bronze badges 7
  • 1 you can use .trim() – guradio Commented Jul 5, 2017 at 3:09
  • So you want to prevent spaces or trim out the spaces? – Andrew Li Commented Jul 5, 2017 at 3:10
  • Use the string method .trim(). What you're doing is removing ALL the spaces in the string. – Gerardo Commented Jul 5, 2017 at 3:10
  • oh thank you. Yes I want remove all spacing – dedi wibisono Commented Jul 5, 2017 at 3:12
  • var newStr = str.replace(/\s+/g, ''); should do what you want – Jaromanda X Commented Jul 5, 2017 at 3:12
 |  Show 2 more ments

1 Answer 1

Reset to default 4

If you want to remove starting and ending spaces use trim()

var value  = "  some text to trim  ";


console.log(value.trim());

If you want to remove all the spaces in entire string use replace

var value = "Some text to replace spaces";
var newStr = value.replace(/\s+/g, '');
console.log(newStr);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论