문자열에 부분 문자열이 포함되어 있는지 어떻게 확인합니까? [복제]
이 질문에 이미 답변이 있습니다.
드롭 다운 메뉴에 제품 옵션을 표시하는 장바구니가 있으며 "예"를 선택하면 페이지의 다른 필드를 표시하고 싶습니다.
문제는 쇼핑 카트에도 텍스트에 가격 수정자가 포함되어 있으며 이는 제품마다 다를 수 있다는 것입니다. 다음 코드가 작동합니다.
$(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();
}
});
});
그러나 나는 차라리 작동하지 않는 다음과 같은 것을 사용하고 싶습니다.
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
선택한 옵션에 "예"라는 단어가 포함 된 경우에만 작업을 수행하고 가격 수정자를 무시합니다.
이렇게 :
if (str.indexOf("Yes") >= 0)
... 또는 물결표 연산자를 사용할 수 있습니다.
if (~str.indexOf("Yes"))
이것은 문자열이 전혀 발견되지 않으면 indexOf()
반환 하기 때문에 작동 -1
합니다.
이것은 대소 문자를 구분합니다.
대소 문자를 구분하지 않는 검색을 원하면 다음과 같이 작성할 수 있습니다.
if (str.toLowerCase().indexOf("yes") >= 0)
또는,
if (/yes/i.test(str))
str.search( 'Yes' )
일치하는 위치를 반환하거나 찾을 수없는 경우 -1을 반환합니다.
이 답변을 작성하는 것은 꽤 늦었지만 어쨌든 포함시킬 생각이었습니다. String.prototype
이제 includes
하위 문자열을 확인할 수 있는 메서드 가 있습니다. 이 방법은 대소 문자를 구분합니다.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
하위 문자열을 확인하려면 다음 방법을 사용할 수 있습니다.
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
자세한 내용 은 설명서 를 확인하십시오 .
또 다른 방법:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Firefox, Safari 6 및 Chrome 36에서 테스트 됨 **
ECMAScript 6은 String.prototype.includes
이전에 contains
.
다음과 같이 사용할 수 있습니다.
'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.
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);
};
}
Returns number of times the keyword is included in the string.
var count = "I have one keyword".match(/keyword/g);
var clean_count = !count ? false : count.length;
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
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);
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.
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.
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";
}
}
}
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
참고URL : https://stackoverflow.com/questions/3480771/how-do-i-check-if-string-contains-substring
'Programing' 카테고리의 다른 글
문자의 ASCII 값을 얻는 방법은 무엇입니까? (0) | 2020.09.28 |
---|---|
.gitignore가 추적되지 않는 파일 목록에 나타나지 않도록하려면 어떻게해야합니까? (0) | 2020.09.28 |
CSS 컨텐츠를 사용하여 HTML 엔티티 추가 (0) | 2020.09.28 |
난독 화 된 C 코드 콘테스트 2006. sykes2.c에 대해 설명해주십시오. (0) | 2020.09.28 |
iOS 앱의 이름을 변경하는 방법은 무엇입니까? (0) | 2020.09.28 |