2

I jquery how to check two values starting with same texts,

My code is

$a = "Hello john";
$b = "Hello peter";

$a == $b --> False

Like this how to find variables staring string.

Vin_fugen
  • 581
  • 3
  • 19
  • 38

4 Answers4

3

Approach 1

Click here for the demo

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function (searchString, position) {
            position = position || 0;
             return this.indexOf(searchString, position) === position;
        }
    });
}


var str = "Pankaj Garg";

alert(str.startsWith("Pankaj"));   // true
alert(str.startsWith("Garg"));     // false
alert(str.startsWith("Garg", 7));  // true

If you pay attention to the third alert, you can start the comparison after leaving some chars also


Approach 2

Click here for the Demo

if (typeof String.prototype.startsWith != 'function') {
      String.prototype.startsWith = function (str){
          return this.indexOf(str) == 0;
  };
}

var data = "Hello world";
var input = 'He';
if(data.startsWith(input))
{
    alert("ok");
}
else
{
    alert("not ok");
}

Approach 3

Check here for the Demo

var str = "Hello A";
var str1 = "Hello B";
if(str.match("^Hello") && str1.match("^Hello")) 
{
    alert('ok');
}
else
{
    alert('not ok');
}
2

If you want to check the first word matches, you could use:

if ($a.split(' ').shift() === $b.split(' ').shift()) {
  // match
}
billyonecan
  • 20,090
  • 8
  • 42
  • 64
1

Or try this http://jsfiddle.net/ApfJz/9/:

var a = "Hello john";
var b = "Hello peter";

alert(startsSame(a, b, 'Hello'));

function startsSame(a, b, startText){
    var indexA = a.indexOf(startText);
    return (indexA == b.indexOf(startText) && indexA >= 0);
}
gregjer
  • 2,823
  • 2
  • 19
  • 18
0
var $a = "Hello john";
var $b = "Hello peter";
if($a.split(" ")[0] == $b.split(" ")[0]) {
  alert('first word matched')
}

Note: This will compare the first word only. Not the entire string.

vinothini
  • 2,606
  • 4
  • 27
  • 42