Henrique Barone
Henrique Barone

Reputation: 153

Determining whether a string has a substring (word)

I try to use a conditional to verify if a string contain a certain word, for example: I want to use a method (regex?) to find if a string has the text "&SWE>clickable".

var text1 = "layer_legs";
var text2 = "layer_head&SWE>clickable";

if (....)
   document.write ("the layer is clickable")
else
   document.write ("the layer is not clickable")

How can I do that?

Upvotes: 0

Views: 168

Answers (5)

David Hellsing
David Hellsing

Reputation: 108500

if (/&SWE>clickable/g.test(text2)) {
    // exists
}

EDIT: Using indexOf like others have posted might be better, since it’s more readable and you don‘t need to escape characters. And arguably faster :/

Upvotes: 0

Cemo
Cemo

Reputation: 5570

 if(text1.indexOf(text2)) 
    document.write ("the layer is clickable") 
 else 
    document.write ("the layer is not clickable")

Upvotes: 0

David Tran
David Tran

Reputation: 10606

try this :

if (text1.indexOf('&SWE>clickable')>=0){ ... }

or regex way :

var re = new RegExp('\&SWE\>clickable')
if (re.test(text1)){ ... }

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

 if (text2.indexOf("&SWE>clickable") > -1) {
    ....

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838176

You can use String.indexOf. It returns -1 if the string is not found, otherwise it returns the index where the string was found. You can use it like this:

if (s.indexOf("&SWE>clickable") !== -1) { ... }

Upvotes: 2

Related Questions