Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Extra Spaces Before and After javascript string [duplicate]

var $one = $('#oneClueShow');
    var x = $("#clueOneInput").find('input[type=text]').val();
    if(x == 'D R' || x == 'd r'|| x == 'D r'|| x == 'd R'|| x == 'd'|| x == 'r' || x == 'd R' || x == 'T A')

Above is a snippet of java/ I have. What it does is takes an input -- then checks for a match. The bug I'm looking to resolve is if there are spaces after or before it isn't recognized.

For example within the input someone can type 'D R' no problem. If a space is added like so 'D R ' then it no longer recognizes the input.

Is there something I can do to affect the input to ensure no space before/after prior to button click? I've been looking into replace, but can't seem to get it going.

A reference for what I've been looking at : http://www.w3schools.com/jsref/jsref_replace.asp

like image 832
user3135730 Avatar asked May 06 '14 02:05

user3135730


Video Answer


2 Answers

You can use $.trim

$.trim(yourstring)

which will allow for cross browser compatibility

In your case it would be

var x = $.trim($("#clueOneInput").find('input[type=text]').val());
like image 199
wirey00 Avatar answered Sep 23 '22 13:09

wirey00


Use the trim() method

Example:

var str = "       Hello World!        ";
alert(str.trim());

This will output :

Hello World!

var str = "       Hello World!        ";
alert(str.trim());
like image 23
Gopinath Koothaperumal Avatar answered Sep 22 '22 13:09

Gopinath Koothaperumal