Substring in String test, like Python: if "this" in thisString

R

Ross

Does anyone have a suggestion for a nice compact test for a substring
in a string? I'm porting some stuff from Python where I can just test
easily with

a="here are some words"
if "are" in a:
print "Yes it's There"

Something tells me a regex is a likely approach...

Thx in advance...
Ross.
 
D

Dmitry A. Soshnikov

Does anyone have a suggestion for a nice compact test for a substring
in a string?  I'm porting some stuff from Python where I can just test
easily with

  a="here are some words"
  if "are" in a:
     print "Yes it's There"

Something tells me a regex is a likely approach...

Thx in advance...
Ross.

'here are some words'.indexOf('are') != -1 && alert('Yes it's There');
 
S

Stevo

Ross said:
Does anyone have a suggestion for a nice compact test for a substring
in a string? I'm porting some stuff from Python where I can just test
easily with

a="here are some words"
if "are" in a:
print "Yes it's There"

Something tells me a regex is a likely approach...

Thx in advance...
Ross.

if ( a.indexOf("are") > -1 )
alert("Yes, it's there");
 
T

Thomas 'PointedEars' Lahn

Ross said:
Does anyone have a suggestion for a nice compact test for a substring
in a string? I'm porting some stuff from Python where I can just test
easily with

a="here are some words"
if "are" in a:
print "Yes it's There"

Something tells me a regex is a likely approach...

You are on the right track:

if (/are/.test(a))
{
console.log("Yes it's There");
}

The presented solution using String.prototype.indexOf() is probably more
efficient with simple expressions but less flexible. For example, given
text that contains only characters that are also in the ASCII character set,
you can search for a word (here: are):

if (/\bare\b/.test(a))
{
console.log("Yes it's There");
}

And you can search case-insensitive:

if (/\bare\b/i.test(a))
{
console.log("Yes it's There");
}

You cannot do this as easily and as efficiently without Regular Expressions.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top