JavaScript로 끝납니다
-
07-07-2019 - |
문제
문자열이 JavaScript에서 특정 문자로 끝 있는지 확인하려면 어떻게해야합니까?
예 : 문자열이 있습니다
var str = "mystring#";
그 줄이 끝나고 있는지 알고 싶어 #
. 어떻게 확인할 수 있습니까?
a
endsWith()
JavaScript의 방법?내가 가진 한 가지 해결책은 문자열의 길이를 가져 와서 마지막 문자를 얻고 확인하는 것입니다.
이것이 가장 좋은 방법입니까 아니면 다른 방법이 있습니까?
해결책
업데이트 (2015 년 11 월 24 일) :
이 답변은 원래 2010 년 (6 년 전)에 게시되었습니다. 따라서 이러한 통찰력있는 의견을 확인하십시오.
Shauna - Googlers의 업데이트 - ECMA6 이이 기능을 추가하는 것처럼 보입니다. MDN 기사는 또한 폴리 필드를 보여줍니다. https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/endswith
TJ 크라우더 - 최신 브라우저에서는 하위 문자열을 만드는 것이 비용이 많이 들지 않습니다. 이 답변이 게시 된 것은 2010 년에 있었을 것입니다. 요즘 간단합니다
this.substr(-suffix.length) === suffix
접근 방식은 Chrome에서 가장 빠르며 IE11에서 indexof와 동일하며 Firefox에서는 4% 느리게 (FergetaboutIt Territory) : jsperf.com/endswith-stackoverflow/14 결과가 거짓 일 때 전반적으로 더 빠릅니다. jsperf.com/endswith-stackoverflow-when-false 물론 ES6이 EndSwith를 추가하면 포인트가 무시됩니다. :-)
원래 답변 :
나는 이것이 1 년 된 질문이라는 것을 알고 있습니다 ... 그러나 나는 이것도 필요하며 크로스 브라우저를 위해 일해야합니다 ... 모든 사람의 대답과 의견을 결합합니다 조금 단순화 :
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
- 서브 스트링을 생성하지 않습니다
- 네이티브를 사용합니다
indexOf
가장 빠른 결과를위한 기능 - 두 번째 매개 변수를 사용하여 불필요한 비교를 건너 뜁니다
indexOf
앞서 건너 뜁니다 - 인터넷 익스플로러에서 작동합니다
- 정수 합병증이 없습니다
또한 기본 데이터 구조의 프로토 타입에서 물건을 채우는 것을 좋아하지 않는다면 여기에 독립형 버전이 있습니다.
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
편집하다: 주석에서 @hamish가 언급 한 바와 같이, 안전한 측면에 오류를하고 구현이 이미 제공되었는지 확인하려면 A를 추가 할 수 있습니다. 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
아마도 가장 좋은 방법 일 것입니다.
Apporach를 보지 못했습니다 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()
메소드는 문자열이 다른 문자열의 문자로 끝나는 지 여부를 결정하여 적절한 경우 true 또는 false를 반환합니다.
통사론
str.endsWith(searchString [, position]);
매개 변수
SearchString :이 문자열의 끝에서 검색 할 문자.
위치 :이 문자열 내 에서이 문자열 이이 길은 것처럼 검색하십시오. 이 문자열의 실제 길이로 기본값은이 문자열의 길이에 의해 설정된 범위 내에서 클램핑됩니다.
설명
이 메소드를 사용하면 문자열이 다른 문자열로 끝나는 지 여부를 결정할 수 있습니다.
예
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? C'mon ...
방금이 문자열 라이브러리에 대해 배웠습니다.
JS 파일을 포함시킨 다음 사용하십시오 S
다음과 같은 변수 :
S('hi there').endsWith('hi there')
Nodejs에서 설치하여 사용할 수 있습니다.
npm install string
그런 다음 그것을 요구합니다 S
변하기 쉬운:
var S = require('string');
웹 페이지에는 대체 문자열 라이브러리에 대한 링크가 있습니다.
Regex를 사용하여 저에게 매력처럼 일한 또 다른 빠른 대안 :
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
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));
}
기존 프로토 타입의 향후 증거 및/또는 덮어 쓰기를 방지하는 방법은 스트링 프로토 타입에 이미 추가되었는지 확인하는 테스트 점검입니다. 다음은 비 Recex 고급 등급 버전에 대한 내 테이크입니다.
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
@chakrit의 받아 들여진 답변은 스스로 할 수있는 확실한 방법입니다. 그러나 포장 된 솔루션을 찾고 있다면 살펴 보는 것이 좋습니다. 밑줄, @mlunoe가 지적했듯이. alterscore.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);
}
};
}
이를 위해서는 밑줄이 필요하지만 밑줄 의존성을 제거하도록 조정할 수 있습니다.
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
;
};
}
이익:
- 이 버전은 단순히 인덱스를 재사용하는 것이 아닙니다.
- 긴 줄에서 가장 큰 성능. 속도 테스트는 다음과 같습니다 http://jsperf.com/starts-ends-with/4
- ECMAScript 사양과 완전히 호환됩니다. 그것은 통과합니다 테스트
정규 표현식을 사용하지 마십시오. 빠른 언어로도 느립니다. 문자열의 끝을 확인하는 함수 만 작성하십시오. 이 라이브러리에는 좋은 예가 있습니다. groundjs/util.js. string.prototype에 함수를 추가하십시오. 이 코드는 그것을 수행하는 방법에 대한 좋은 예가 있습니다. groundjs/prototype.js일반적으로 이것은 좋은 언어 수준의 라이브러리입니다. groundjsLodash를 볼 수도 있습니다
그들 모두는 매우 유용한 예입니다. 첨가 String.prototype.endsWith = function(str)
문자열이 끝인지 확인하기 위해 간단히 메소드를 호출하는 데 도움이 될 것입니다. 잘 regexp도 할 것입니다.
나는 내 것보다 더 나은 해결책을 찾았다. 감사합니다.
커피 스크립트
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length