programing

jQuery에서 문자열이 특정 문자열로 시작/종료되는지 확인하는 방법

firstcheck 2022. 10. 18. 21:56
반응형

jQuery에서 문자열이 특정 문자열로 시작/종료되는지 확인하는 방법

문자열이 지정된 문자/문자열로 시작하는지 아니면 jQuery로 끝남을 알고 싶습니다.

예:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

만약 어떤 기능이 없다면, 다른 대안이 있나요?

하나의 옵션은 정규 표현을 사용하는 것입니다.

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}

starts Of 의 경우는, index Of 를 사용할 수 있습니다.

if(str.indexOf('Hello') == 0) {

...

레퍼런스

문자열 길이에 따라 계산하여 'endswith'를 결정할 수 있습니다.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

그것을 하기 위해 jQuery를 사용할 필요는 없습니다.jQuery 래퍼를 코드화할 수 있지만 쓸모없기 때문에 사용하는 것이 좋습니다.

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

match() 메서드는 권장되지 않습니다.

PS : RegExp의 "i" 플래그는 옵션이며 대소문자를 구분하지 않습니다(따라서 "hello", "hello" 등의 경우에도 true가 반환됩니다).

이러한 작업에는 jQuery가 실제로 필요하지 않습니다.ES6 사양에서는 이미 즉시 사용 가능한 메서드가 시작됩니다.과 끝.

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

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

현재 FF와 Chrome으로 제공되고 있습니다.오래된 브라우저에서는 폴리필 또는 기판을 사용할 수 있습니다.

늘리면 요.String다음과 같이 합니다.

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

그리고 이렇게 사용하세요.

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

는 ES6를 .startsWith() ★★★★★★★★★★★★★★★★★」endsWith()string을 지원하는 중 를 s. pre-es6에 .String프로토타입입니다.

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true

언급URL : https://stackoverflow.com/questions/3715309/how-to-know-that-a-string-starts-ends-with-a-specific-string-in-jquery

반응형