itsource

JavaScript로 끝남

mycopycode 2022. 12. 24. 17:28
반응형

JavaScript로 끝남

JavaScript에서 문자열이 특정 문자로 끝나는지 확인하려면 어떻게 해야 합니까?

예:나는 끈이 있다

var str = "mystring#";

이 with음음음음음음음음음음음음음음음음음음음음 with i i i i i i i i i i로 싶습니다.#떻게확 확인 ?? ???

  1. endsWith()자바스크립트?

  2. 제가 가지고 있는 해결책 중 하나는 문자열의 길이를 가져다가 마지막 문자를 받아서 확인하는 것입니다.

이게 최선인가요 아니면 다른 방법이 있나요?

업데이트 (2015년 11월 24일) :

이 답변은 원래 2010년(6년 전)에 게시되었으므로 다음과 같은 통찰력 있는 의견을 참고하십시오.

구글 업데이트 - ECMA6에 이 기능이 추가된 것 같습니다.MDN 문서에는 폴리필도 기재되어 있습니다.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

  • T.J. 크로더-

서브스트링을 만드는 것은 현대의 브라우저에서 비싸지 않다.이 답변이 게시된 것은 2010년이었을지도 모른다.한 '아예'가this.substr(-suffix.length) === suffix 접근법은 Chrome에서 가장 빠르고, IE11에서 indexOf와 같으며, Firefox에서는 4%(fergetabout territory)만 느립니다.https://jsben.ch/OJzlM 및 결과가 잘못된 경우: jsperf.com/endswith-stackoverflow-when-falseOf course, ES6 adding ends With, 포인트는 moot. : - ).


원래 답변:

1년 전 질문인 건 알지만...하지만 이것도 필요하고 크로스브라우저도 작동해야 하니까...모두의 답변과 코멘트를 조합해, 조금 심플하게 합니다.

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)

는 모든 패치 적용은 StringlastIndexOf이치

정규 할 수 예: " 음음음음 charact charact charact charact if '$'을 사용하다

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}

이렇게 쓸 수 있어요.

makeSuffixRegExp("a[complicated]*suffix*").test(str)
  1. 아쉽게도 아닙니다.
  2. if( "mystring#".substr(-1) === "#" ) {}

이에요.endsWith★★★★

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

를 사용합니다.lastIndexOf일치하지 않을 경우 불필요한 CPU 루프가 생성됩니다.

이 버전에서는 하위 문자열이 생성되지 않으며 정규 표현식을 사용하지 않습니다(여기에 있는 일부 regex 응답은 작동하지만 다른 응답은 중단됨).

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

에게 성과가 중요하다면, 해 볼 가 입니다.lastIndexOf 수 더 수 작을 클 때는 쓰지 가 있습니다. )을(를) 사용하다스트링이 작을 경우 스트링이 클 때는 별로 신경 쓰지 않아도 전체를 돌아볼 필요가 있습니다.

후, 「」, 「」를 사용합니다.charAt★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

의 부속품을 찾을 수 없었습니다.slice방법.그래서 그냥 여기 놔둘게요.

function endsWith(str, suffix) {
    return str.slice(-suffix.length) === suffix
}

developer.mozilla.org 에서 String.protype.endsWith() 로부터

요약

endsWith()method는 문자열이 다른 문자열의 문자로 끝날지 여부를 결정하며 필요에 따라 true 또는 false를 반환합니다.

구문

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)

브라우저 호환성

브라우저 호환성

return this.lastIndexOf(str) + str.length == this.length;

는 원래 문자열 길이가 검색 문자열 길이보다1개 작을 때 검색 문자열을 찾을 수 없는 경우 작동하지 않습니다.

lastIndexOf는 -1을 반환하고 검색 문자열 길이를 추가하면 원래 문자열의 길이가 남습니다.

생각할 수 있는 해결 방법은

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
if( ("mystring#").substr(-1,1) == '#' )

-- 또는 --

if( ("mystring#").match(/#$/) )

regex를 사용하여 내게 매력적으로 작용한 또 다른 빠른 대안:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
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!

왜 정규 표현일까요?왜 프로토타입을 만지작거리죠?기판?어서...

이 문자열 라이브러리에 대해 방금 알게 되었습니다.

http://stringjs.com/

js 파일을 포함시킨 후S다음과 같은 변수:

S('hi there').endsWith('hi there')

노드에서도 사용할 수 있습니다.JS 설치:

npm install string

그 후, 그 요구는S변수:

var S = require('string');

웹 페이지에는 다른 문자열 라이브러리로 연결되는 링크도 있습니다.

lodash를 사용하는 경우:

_.endsWith('abc', 'c'); // true

lodash를 사용하지 않을 경우 lodash 소스로부터 빌릴 수 있습니다.

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, '#');
}

그 많은 답을 모은 후에, 나는 이 코드 조각이 간단하고 이해하기 쉽다는 것을 알았다.

function end(str, target) {
  return str.substr(-target.length) == target;
}

lasIndexOf 또는 기판을 사용하지 않는 경우 자연상태의 문자열(어레이)을 보면 됩니다.

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)/));

이는 @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
        ;
    };
}

이점:

  • 이 버전은 indexOf만 재사용하는 것이 아닙니다.
  • 롱 스트링으로 최고의 퍼포먼스를 발휘합니다.다음은 속도 테스트입니다.http://jsperf.com/starts-ends-with/4
  • 에코스크립트 사양과 완전히 호환됩니다.시험에 합격하다

정규 표현은 사용하지 마십시오.그들은 빠른 언어에서도 느리다.문자열의 끝을 체크하는 함수를 작성하기만 하면 됩니다.이 라이브러리에는 groundjs/util.js 등의 좋은 예가 있습니다.String.protype에 함수를 추가하는 데 주의하십시오.이 코드에는 그 실행 방법의 좋은 예가 있습니다.groundjs/protype.js 일반적으로 이것은 훌륭한 언어 수준의 라이브러리입니다.groundjs lodash도 참조할 수 있습니다.

그것들은 모두 매우 유용한 예이다." " " String.prototype.endsWith = function(str)이 메서드를 호출하여 문자열이 그것으로 끝나는지 확인하는 데 도움이 됩니다.well regexp도 이 메서드를 호출합니다.

나는 나보다 더 좋은 해결책을 찾았다.모두 감사합니다.

cofeescript의 경우

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length

이 바로 이은, 의입니다다ation이다의 입니다.endsWith:

String.prototype.endsWith = function (str) {
  return (this.length >= str.length) && (this.substr(this.length - str.length) === str);
}

7년 전의 투고입니다만, 몇개의 투고는 복잡하기 때문에 이해할 수 없었습니다.그래서 저는 저만의 해결책을 썼습니다.

function strEndsWith(str, endwith)
{
    var lastIndex = url.lastIndexOf(endsWith);
    var result = false;
    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
    {
        result = true;
    }
    return result;
}

언급URL : https://stackoverflow.com/questions/280634/endswith-in-javascript

반응형