Question

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

Was it helpful?

Solution

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());

OTHER TIPS

Use the trim() method

Example:

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

This will output :

Hello World!

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

You may use the trim() method.

Do this for cross-browser:

var x = $("#clueOneInput").find('input[type=text]').val().replace(/^\s+|\s+$/g,"");

You can do a check before-hand:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.toString().replace(/^\s+|\s+$/g, '');
  };
}

Will enable .trim in non-supported browsers. And then, you can use it like:

 var x = $("#clueOneInput").find('input[type=text]').val().trim();

With the benefit that you can use this .trim method at many other places in the code too.

You should always use $.trim() while comparing the string. You can use $.trim() like:

  if($.trim(x) == 'D R' || $.trim(x) == 'd r'|| $.trim(x) == 'D r'|| $.trim(x) == 'd R'|| $.trim(x) == 'd'|| $.trim(x) == 'r' || $.trim(x) == 'd R' || $.trim(x) == 'T A')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top