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
1 Answer
Reset to default 4If 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>