I have a shopping cart that displays product options in a dropdown menu and if they select “yes”, I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str == "Yes (+ $6.95)") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn’t work:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word “Yes”, and would ignore the price modifier.
cнŝdk
31.2k7 gold badges55 silver badges77 bronze badges
asked Aug 13, 2010 at 21:25
3
Like this:
if (str.indexOf("Yes") >= 0)
…or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf()
returns -1
if the string wasn’t found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
The latter is a regular expression or regex.
Regex breakdown:
/
indicates this is a regexyes
means that the regex will find those exact characters in that exact order/
ends the regexi
sets the regex as case-insensitive.test(str)
determines if the regular expression matchesstr
To sum it up, it means it will see if it can find the lettersy
,e
, ands
in that exact order, case-insensitively, in the variablestr
RedGuy11
3446 silver badges14 bronze badges
answered Aug 13, 2010 at 21:28
SLaksSLaks
863k176 gold badges1900 silver badges1961 bronze badges
2
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn’t found.
answered Aug 13, 2010 at 21:29
hookedonwinterhookedonwinter
12.4k19 gold badges61 silver badges74 bronze badges
2
It’s pretty late to write this answer, but I thought of including it anyhow. String.prototype
now has a method includes
which can check for substring. This method is case sensitive.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentation to know more.
answered May 7, 2016 at 13:38
MunimMunim
2,6061 gold badge19 silver badges28 bronze badges
1
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
az7ar
5,1572 gold badges16 silver badges23 bronze badges
answered Feb 20, 2013 at 19:44
Andy BrahamAndy Braham
9,4594 gold badges46 silver badges56 bronze badges
1
ECMAScript 6 introduces String.prototype.includes
, previously named contains
.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
answered Apr 16, 2016 at 23:00
OriolOriol
269k62 gold badges428 silver badges505 bronze badges
0
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
answered Nov 18, 2016 at 17:45
Parth RavalParth Raval
3,9793 gold badges23 silver badges36 bronze badges
0
You can use this Polyfill in ie and chrome
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
answered Jul 3, 2013 at 14:09
robkorvrobkorv
5397 silver badges5 bronze badges
0
If you are capable of using libraries, you may find that Lo-Dash JS library is quite useful. In this case, go ahead and check _.contains()
(replaced by _.includes()
as of v4).
(Note Lo-Dash convention is naming the library object _.
Don’t forget to check installation in the same page to set it up for your project.)
_.contains("foo", "oo"); // → true
_.contains("foo", "bar"); // → false
// Equivalent with:
_("foo").contains("oo"); // → true
_("foo").contains("bar"); // → false
In your case, go ahead and use:
_.contains(str, "Yes");
// or:
_(str).contains("Yes");
..whichever one you like better.
answered Oct 1, 2015 at 6:18
SelfishSelfish
5,9553 gold badges42 silver badges63 bronze badges
0
I know that best way is str.indexOf(s) !== -1;
http://hayageek.com/javascript-string-contains/
I suggest another way(str.replace(s1, "") !== str
):
var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);
answered Oct 1, 2015 at 6:05
You can also check if the exact word is contained in a string. E.g.:
function containsWord(haystack, needle) {
return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}
Usage:
containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false
This is how jQuery does its hasClass method.
answered Mar 26, 2015 at 15:43
bashausbashaus
1,6021 gold badge16 silver badges33 bronze badges
you can define an extension method and use it later.
String.prototype.contains = function(it)
{
return this.indexOf(it) != -1;
};
so that you can use in your page anywhere like:
var str="hello how are you";
str.contains("are");
which returns true.
Refer below post for more extension helper methods.
Javascript helper methods
answered Mar 3, 2015 at 13:08
Vikas KottariVikas Kottari
4952 gold badges10 silver badges24 bronze badges
None of the above worked for me as there were blank spaces but this is what I did
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
bottab.style.display="none";
bottab2.style.display="none";
if (td) {
var getvar=td.outerText.replace(/s+/, "") ;
if (getvar==filter){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}
answered Jul 17, 2017 at 0:14
$a = 'how are you';
if (strpos($a,'are') !== false) {
echo 'true';
}
In PHP, we can use the code above to check if a string contain specific words, but how can I do the same function in JavaScript/jQuery?
j08691
203k31 gold badges259 silver badges271 bronze badges
asked Mar 22, 2011 at 8:18
Charles YeungCharles Yeung
38.2k30 gold badges90 silver badges130 bronze badges
4
you can use indexOf for this
var a = 'how are you';
if (a.indexOf('are') > -1) {
return true;
} else {
return false;
}
Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if
clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,
var a = 'how are you';
return a.indexOf('are') > -1;
Update in ECMAScript2016:
var a = 'how are you';
return a.includes('are'); //true
answered Mar 22, 2011 at 8:22
3
indexOf
/includes
should not be used for finding whole words:
A word (in western culture) is a drawing of a symbols close to each other, with some space between each word. A word is considered as such if it’s a complete piece of characters draw together and not a partial part of it:
"has a word".indexOf('wor') // 6 ("wor" is not a word in this sentence)
"has a word".includes('ha') // true ("ha" is not a word in this sentence)
Check if a single word (whole word) is in the string
Find a real whole word, not just if the letters of that word are somewhere in the string.
const wordInString = (s, word) => new RegExp('\b' + word + '\b', 'i').test(s);
// tests
[
'', // true
' ', // true
'did', // true
'id', // flase
'yo ', // flase
'you', // true
'you not' // true
].forEach(q => console.log(
wordInString('dID You, or did you NOt, gEt WHy?', q)
))
console.log(
wordInString('did you, or did you not, get why?', 'you') // true
)
Check if all words are in the string
var stringHasAll = (s, query) =>
// convert the query to array of "words" & checks EVERY item is contained in the string
query.split(' ').every(q => new RegExp('\b' + q + '\b', 'i').test(s));
// tests
[
'', // true
' ', // true
'aa', // true
'aa ', // true
' aa', // true
'd b', // false
'aaa', // false
'a b', // false
'a a a a a ', // false
].forEach(q => console.log(
stringHasAll('aA bB cC dD', q)
))
answered Jan 12, 2014 at 23:41
vsyncvsync
116k56 gold badges302 silver badges392 bronze badges
6
If you are looking for exact words and don’t want it to match things like “nightmare” (which is probably what you need), you can use a regex:
/bareb/gi
b = word boundary
g = global
i = case insensitive (if needed)
If you just want to find the characters “are”, then use indexOf
.
If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test
.
answered Mar 22, 2011 at 8:27
Stephen ChungStephen Chung
14.5k1 gold badge35 silver badges48 bronze badges
You’re looking for the indexOf function:
if (str.indexOf("are") >= 0){//Do stuff}
answered Mar 22, 2011 at 8:22
evbaileyevbailey
3713 silver badges11 bronze badges
You might wanna use include method in JS.
var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.
PS: includes is case sensitive.
answered Apr 16, 2018 at 7:26
In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.
var str = "Hello there.";
var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her"); //true
var check4 = str.includes("o",4); //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6); //false o is not at position 6
answered Oct 20, 2019 at 8:09
ZeniZeni
9071 gold badge11 silver badges24 bronze badges
1
An easy way to do it to use Regex match() method :-
For Example
var str ="Hi, Its stacks over flow and stackoverflow Rocks."
// It will check word from beginning to the end of the string
if(str.match(/(^|W)stack($|W)/)) {
alert('Word Match');
}else {
alert('Word not found');
}
Check the fiddle
NOTE: For adding case sensitiveness update the regex with /(^|W)stack($|W)/i
Thanks
Vineeth Sai
3,3897 gold badges22 silver badges34 bronze badges
answered Sep 20, 2018 at 6:33
This will
/bwordb/.test("Thisword is not valid");
return false
, when this one
/bwordb/.test("This word is valid");
will return true
.
answered Jun 19, 2015 at 17:07
JahidJahid
21.2k9 gold badges89 silver badges107 bronze badges
var str1 = "STACKOVERFLOW";
var str2 = "OVER";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}
answered Aug 29, 2018 at 6:09
Using a conditional ternary operator
str = 'I am on StackOverflow';
str.match(/(^|W)StackOverflow($|W)/) ? 'Found. Why lie?' : 'Not Found';
answered Jan 21, 2022 at 20:28
WiiLFWiiLF
3043 silver badges11 bronze badges
If you’d like to find a single word in a string without regular expressions, you can do as follows:
function isWordInString(needle, haystack) {
return haystack
.split(' ')
.some(p => (p === needle));
}
isWordInString('hello', 'hello great world!'); // true
isWordInString('eat', 'hello great world!'); // false
Advantages over regex:
- Works with non-latin characters like Hebrew
- No need to sanitize the word you search in the string. Some methods in other answers will fail and return a false positive when searching for a “.” (dot)
answered Jun 8, 2022 at 9:42
ArikArik
5,1181 gold badge26 silver badges26 bronze badges
Вы получаете некий текст в ваш скрипт, и ваша задача – проверить, присутствует ли нужная вам фраза в этом тексте или нет, и в последующем, при положительном раскладе вещей, выполнить какое-то действие.
Поставленные задачи легко решаются с помощью PHP и JavaScript, а как именно – я сейчас расскажу.
Как проверить наличие слова, фразы или текста в строке на PHP
В PHP существуют два способа, с помощью которых можно узнать наличие искомой фразы в строке.
Первый способ – это регулярные выражения. Здесь мы используем функцию «preg_match» для обхода по всему тексту.
Реализация:
<?php
$content = "Hello, World!";
if(preg_match("/World/", $content)) {
echo "Слово найдено";
}
?>
И, соответственно, то же самое для отрицания:
<?php
$content = "Hello, World!";
if(!preg_match("/PHP/", $content)) {
echo "Слово не найдено";
}
?>
Помимо этого, есть и второй способ – это функция «strpos», которая возвращает позицию первого вхождения указанной фразы.
Использование:
<?php
$content = "Hello, World!";
if(strpos($content, "World") !== false) {
echo "Слово найдено";
}
?>
И то же самое для отрицания:
<?php
$content = "Hello, World!";
if(strpos($content, "PHP") === false) {
echo "Слово не найдено";
}
?>
Если вы ищете небольшие участки текста, то в таком случае для использования предпочтителен второй вариант – так как он менее ресурсоемкий.
Как проверить наличие слова, фразы или текста в строке на JavaScript
На JavaScript осуществить проверку наличия текста в строке можно несколькими способами.
Один из которых – все те же регулярные выражения.
Пример реализации:
<script>
var pattern = /World/;
var content = "Hello, World!";
var exists = pattern.test(content);
if(exists) {
alert("Слово найдено");
}
</script>
И то же самое для отрицания:
<script>
var pattern = /PHP/;
var content = "Hello, World!";
var exists = pattern.test(content);
if(!exists) {
alert("Слово не найдено");
}
</script>
Еще один рабочий вариант решения проблемы – это метод «indexOf», который помогает подсчитать количество совпадений при поиске.
Реализация:
<script>
var pattern = "World";
var content = "Hello, World!";
if(content.indexOf(pattern) !== -1) {
alert("Слово найдено");
}
</script>
И то же самое для отрицания:
<script>
var pattern = "PHP";
var content = "Hello, World!";
if(content.indexOf(pattern) === -1) {
alert("Слово не найдено");
}
</script>
В обоих способах существенной разницы в скорости нет – используйте тот, что более удобен для вас.