0

Anyway that I can check for string inside a string in javascript?

Example: If I have 2 variable

var value1 = '|1|2|3|4|5|6'
var value2 = '1|2|3'

How can I check whether value2 is found in value1?

asked Nov 11, 2010 at 3:51

3 Answers 3

6
var contained = (value1.indexOf(value2) != -1);

contained will be true if and only if value2 is a substring of value1.

answered Nov 11, 2010 at 3:53
Sign up to request clarification or add additional context in comments.

1 Comment

To be clear, this will return the 0-based index of the start of where value2 occurs within value1; it will return -1 if it is not found, so make sure to code any conditions accordingly. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
0
'|1|2|3|4|5|6'.match(/1\|2\|3/);

Note that you need to escape the |, since they have a special meaning in Regular Expressions. If this is too much of a hassle, Matthews indexOf method is easier.

answered Nov 11, 2010 at 3:55

Comments

0

I like to use regular expressions and javascript's .match() method:

if(value1.match(/1\|2\|3/)) {
 // value2 is found in value1
}

.match() returns an array of the matches, or null if no matches are found.

Also note that the pipes, |, have to be escaped with a backslash, \, because they have special meaning within regular expressions. Specifically, they mean OR. So /1|2/ becomes 1 OR 2. While if we escape the | with a backslash like so:

/1\|2/

It becomes:

1|2
answered Nov 11, 2010 at 3:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.