Question

I'm trying to format the users input so that it can meet the conditions in my string comparison function, as you know with string comparison extra spaces, tabs, and "enter(newline)" are considered. So the idea is format the users input before running string comparison function. Currently extra spaces, tabs and the "enter(newline)" problem has been partially solved.

Here's my code and a fiddle: http://jsfiddle.net/eSE9Y/2/

html

<textarea id="address"></textarea>
<input type="button" id="Validate" value="Validate" onClick="valbtn()">

javascript

$(document).ready(function(){
    $("#Validate").click(function () {
    $('#address').val($('#address').val().replace(/\s+/g,' '));
    });
});

But the problem is if a users first and ending input is enter or a space, it will still mess up the string comparison function, until I find the PHP trim, how can i utilize this php function to fit/solve the problem. Any suggestion/opinion is appreciated.

Was it helpful?

Solution

You know about the JavaScript trim() function, right? Or the jQuery $.trim() function?

trim():

The trim() method removes whitespace from both ends of the string.

Usage:

$("#Validate").click(function () {
    $('#address').val(function() { return this.value.trim(); });
});

jsFiddle Demo


$.trim():

Description: Remove the whitespace from the beginning and end of a string.

Usage:

$("#Validate").click(function () {
    $('#address').val(function() { return $.trim($(this).val()); });
});

jsFiddle Demo

OTHER TIPS

Either you can use trim()

$(document).ready(function(){
    $("#Validate").click(function () {
    $('#address').val($('#address').val().replace(/\s+/g,' ').trim())
    });
});

FFIDDLE

or you can use replace()

$(document).ready(function(){
    $("#Validate").click(function () {
    $('#address').val($('#address').val().replace(/\s+/g,' ').replace(/\s+$/g,'').replace(/^\s+/g,''));
    });
});

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top