How to do this type of comparison.
Say i have a variable with a word "ABCDEF"
and i want to check the combination "DEF" exists in it or not how do i do?
I want to make a simple comparison test..
Some friend suggested me the "substring" function but that works only in JSP i hope?

Please help me out!

Recommended Answers

All 3 Replies

Use the indexOf() method of the string object:

var string_a = "ABCDEF";
var string_b = "DEF";
var iof_b = string_a.indexOf( string_b );
if( iof_b == -1 )
{
  alert( "Cannot find the string " + string_b + " in " + string_a );
}
else
{
  alert( "Found the string " + string_b + " in " + string_a + " at character index " + iof_b );
}

You can certainly do what as Matt suggests. However, in the longer term if you plan to use JS a lot you would be better of learning to use regular expressions. Not necessary in this instance but the power they offer is well worth having under your belt. Here is the RegEx solution to your question

function Test()
 {
   var r = new RegExp("DEF");
   var s = "ABCDEF"
   document.write(r.test(s));
  }

This will write the string 'true' to your document. Naturally, you will want to do something else with the result.

Look here

http://www.regular-expressions.info

for an exhaustive discussion of regular expressions. Do note though that JS regular expressions are no way as powerful as in Perl etc.

lots of thanx for your help..
i used this method..

if(string1.search(string2)==-1)
    {
   // Not found
    }
    else
    {
  //  found
    }

see if that is usefull
cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.