JavaScript에서 endsWith
JavaScript에서 어디에서나 특정 문자로 끝나는 지 어떻게 확인할 수 있습니까?
예 : 이미 있습니다.
var str = "mystring#";
그 공유 이로 끝나는 지 알고 싶습니다 #
. 어떻게 서열 수 있습니까?
거기에
endsWith()
자바 펼쳐의 방법은?내가 가진 한 가지 방법은 길이를 가져와 마지막 문자를 가져와 확인하는 것입니다.
가장 최선의 방법입니까?
업데이트 (2015 년 11 월 24 일) :
이 답변은 원래 2010 년 (6 년 전)에 게시 된 결과 다음과 같은 검증 된 의견에 유의하십시오.
Shauna -Google 직원을위한 업데이트 -ECMA6 가이 기능을 추가 할 수 있습니다. MDN 기사는 또한 polyfill을 보여줍니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
TJ Crowder- 최신 브라우저에서는 하위를 만드는 데 비용이 많이 들지 않습니다. 이 답변이 게시 된 2010 년이었을 것입니다. 요즘은 간단한
this.substr(-suffix.length) === suffix
접근 방식이 Chrome에서 가장 빠른 IE11에서 indexOf와 동일하며 Firefox에서는 4 % 만 느립니다 (fergetaboutit). jsperf.com/endswith-stackoverflow/14 결과가 전반적으로 더 빠입니다. jsperf.com/endswith-stackoverflow-when-false 물론 ES6가 endsWith를 추가하면 요점은 논란의 여지가 있습니다. :-)
원래 답변 :
나는 이것이 오래된 질문이라는 것을 알고 있습니다 ...하지만 이것도 필요하고 브라우저 간 작업을 필요합니다. 그래서 ... 모든 사람의 대답과 의견을 결합 하고 단순화합니다.
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
- 부분을 생성하지 않습니다.
indexOf
가장 빠른 결과를 위해 기본 기능 사용- 두 번째 매개 변수를 사용하여 불필요한 비교
indexOf
를 건너 뛰었습니다. - Internet Explorer에서 작동
- 정규식 합병증 없음
또한 외장형 데이터 구조를 제공하는 것을 좋아하지 않는 경우 여기에 독립형 버전이 있습니다.
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
편집 : 주석에서 @hamish가 참조했듯이 안전한에서 실수하고 구현이 이미 제공 typeof
되었는지 확인한 다음과 같이 확인을 추가하면 됩니다.
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
/#$/.test(str)
모든 브라우저에서 작동하고 원숭이 패치 String
가 lastIndexOf
필요하지 않습니다. 일치하는 항목이 없을 때 처럼 전체를 스캔 할 필요 가 없습니다.
와 같은 정규식 특수 문자를 포함 할 수있는 상수를 찾을 수 있습니다. 시키려면 '$'
다음을 사용할 수 있습니다.
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
다음과 같이 사용할 수 있습니다.
makeSuffixRegExp("a[complicated]*suffix*").test(str)
- 불행히도.
if( "mystring#".substr(-1) === "#" ) {}
자, 이것이 올바른 endsWith
구현입니다.
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
사용 lastIndexOf
하면 일치하는 항목이없는 경우 불필요한 CPU 루프가 생성됩니다.
이 버전은 하위 하위 생성을 피하고 정규식을 사용하지 않습니다. (일부 정규식 작동하고 나머지는 손상됨).
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
성능이 중요하다면 lastIndexOf
하위에 만드는 것보다 빠른지 여부를 테스트 해 볼 가치가 있습니다 . (사용하는 JS 엔진에 따라 다를 수 있습니다 ...) 일치하는 경우 더 빠를 수 있습니다 크면 전체를 다시보기합니다. 우리는 신경 쓰지 않지만 :(
단일 문자를 확인 charAt
하는 것이 가장 좋은 방법 일 것입니다.
slice
방법에 대한 접근을 보지에 . 그래서 여기에 두겠습니다.
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
return this.lastIndexOf(str) + str.length == this.length;
언어 언어 길이가 검색 길이보다 짧고 검색을 사용할 수 있습니다.
lastIndexOf는 -1을 반환하고 검색 길이를 추가로 늘이고 길이가 남습니다.
가능한 해결 방법은
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
developer.mozilla.org에서 String.prototype.endsWith ()
요약
이 endsWith()
메소드는 암호화 된 언어의 문자로 끝나는 지 여부를 확인하여 참 또는 거짓을 반환합니다.
통사론
str.endsWith(searchString [, position]);
매개 변수
searchString :이 노드의 끝에서 검색 할 문자입니다.
position : 이숭 숭숭 배 이이 길이 만있는 것처럼 여기에서 검색합니다. 길이는 길이가 높은 것입니다.
기술
이 방법을 사용하면 쉽게 사용할 수 있습니다.
예
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
요약
ECMAScript 언어 사양 6 판 (ECMA-262)
브라우저
if( ("mystring#").substr(-1,1) == '#' )
-또는-
if( ("mystring#").match(/#$/) )
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
이게 도움이 되길 계속
var myStr = “ Earth is a beautiful planet ”;
var myStr2 = myStr.trim();
//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…
방법 방법
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
나는 당신에 대해 모르지만 :
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
왜 정규식인가? 왜 만드는 타입을 엉망으로 만드나요? substr? 어서 ...
lodash를 사용하는 경우 :
_.endsWith('abc', 'c'); // true
lodash를 사용하지 않는 경우 소스 에서 빌릴 수 있습니다 .
정규식을 사용하여 나를 위해 매력처럼 작동하는 또 다른 대안 대안 :
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
이 라이브러리에 방금 방금 배웠습니다.
js 파일을 포함하고 다음 S
과 같은 변수 를 사용합니다 .
S('hi there').endsWith('hi there')
NodeJS를 설치하여 사용할 수도 있습니다.
npm install string
그런 다음 S
변수 로 필요 :
var S = require('string');
웹 페이지에는 대체 문자열 라이브러리에 대한 링크도 있습니다.
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
이런 작은 문제에 대한 많은 것들이 있습니다.이 정규식을 사용하십시오.
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}
이 질문에 대해 수년이 걸렸습니다. 가장 많이 득표 한 chakrit의 답변을 사용하려는 사용자를 위해 중요한 업데이트를 추가하겠습니다.
'endsWith'함수는 ECMAScript 6 (실험 기술)의 일부로 JavaScript에 이미 추가되었습니다.
여기에서 참조하십시오 : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
따라서 답변에서 언급했듯이 네이티브 구현의 존재 여부를 확인하는 것이 좋습니다.
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
미래의 증명 및 / 또는 기존 프로토 타입의 덮어 쓰기를 방지하는 방법은 이미 String 프로토 타입에 추가되었는지 확인하는 테스트 검사입니다. 정규식이 아닌 높은 등급의 버전에 대한 나의 견해는 다음과 같습니다.
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
@chakrit의 대답은 스스로 할 수있는 확실한 방법입니다. 그러나 패키지 솔루션을 찾고 있다면 @mlunoe가 지적한 것처럼 underscore.string을 살펴 보는 것이 좋습니다 . underscore.string을 사용하면 코드는 다음과 같습니다.
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
lasIndexOf 또는 substr을 사용하고 싶지 않다면 자연 상태 (즉, 배열)에서 문자열을 보는 것은 어떻습니까?
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
또는 독립형 기능으로
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
String.prototype.endWith = function (a) {
var isExp = a.constructor.name === "RegExp",
val = this;
if (isExp === false) {
a = escape(a);
val = escape(val);
} else
a = a.toString().replace(/(^\/)|(\/$)/g, "");
return eval("/" + a + "$/.test(val)");
}
// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));
그 긴 답변 끝에 나는이 코드 조각이 간단하고 이해하기 쉽다는 것을 알았습니다!
function end(str, target) {
return str.substr(-target.length) == target;
}
이것은 endsWith의 구현입니다.
String.prototype.endsWith = function (str) {return this.length> = str.length && this.substr (this.length-str.length) == str; }
이것은 endsWith의 구현입니다. String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }
이것은 문자열 배열 또는 문자열이 인수로 전달되도록 허용하는 @charkit의 허용 응답을 기반으로합니다.
if (typeof String.prototype.endsWith === 'undefined') {
String.prototype.endsWith = function(suffix) {
if (typeof suffix === 'String') {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
}else if(suffix instanceof Array){
return _.find(suffix, function(value){
console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
return this.indexOf(value, this.length - value.length) !== -1;
}, this);
}
};
}
여기에는 underscorejs가 필요하지만 밑줄 종속성을 제거하도록 조정할 수 있습니다.
if(typeof String.prototype.endsWith !== "function") {
/**
* String.prototype.endsWith
* Check if given string locate at the end of current string
* @param {string} substring substring to locate in the current string.
* @param {number=} position end the endsWith check at that position
* @return {boolean}
*
* @edition ECMA-262 6th Edition, 15.5.4.23
*/
String.prototype.endsWith = function(substring, position) {
substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;
else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)
&& (
position === 0
// if position not at the and of the string, we can optimise search substring
// by checking first symbol of substring exists in search position in current string
|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
)
&& this.indexOf(substring, fromIndex) === fromIndex
;
};
}
혜택:
- 이 버전은 indexOf를 재사용하는 것만이 아닙니다.
- 긴 스트링에서 최고의 성능. 다음은 속도 테스트입니다. http://jsperf.com/starts-ends-with/4
- ecmascript 사양과 완벽하게 호환됩니다. 테스트를 통과했습니다.
정규식을 사용하지 마십시오. 빠른 언어에서도 느립니다. 문자열의 끝을 확인하는 함수를 작성하십시오. 이 라이브러리는 좋은 사례가 있습니다 groundjs / util.js . String.prototype에 함수를 추가하는 데주의하십시오. 이 코드에는이를 수행하는 방법에 대한 멋진 예제가 있습니다. groundjs / prototype.js 일반적으로 이것은 멋진 언어 수준 라이브러리입니다. groundjs lodash를 살펴볼 수도 있습니다.
모두 매우 유용한 예입니다. 추가 String.prototype.endsWith = function(str)
하면 단순히 메서드를 호출하여 문자열이 끝나는 지 여부를 확인하는 데 도움이됩니다. regexp도이를 수행합니다.
나는 내 것보다 더 나은 해결책을 찾았습니다. 모두 감사합니다.
coffeescript 용
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length
참고 URL : https://stackoverflow.com/questions/280634/endswith-in-javascript
'ProgramingTip' 카테고리의 다른 글
AWS가있을 때 사람들이 Heroku를 사용하는 이유는 무엇입니까? (0) | 2020.09.27 |
---|---|
JavaScript에서 2 차원 배열을 어떻게 만들 수 있습니까? (0) | 2020.09.27 |
그리드 레이아웃에서 플링 제스처 감지 (0) | 2020.09.27 |
인쇄 기능의 출력을 어떻게 플러시하고? (0) | 2020.09.27 |
어디에 있습니까? (0) | 2020.09.27 |