development

Javascript를 사용하여 문자열에서 문자를 제거하려면 어떻게해야합니까?

big-blog 2020. 3. 16. 08:23
반응형

Javascript를 사용하여 문자열에서 문자를 제거하려면 어떻게해야합니까?


나는 이것을 얻는 것에 너무 가깝지만, 옳지 않다. 내가하고 싶은 r것은 문자열 에서 문자 제거하는 것 입니다. 문제는 r문자열에 인스턴스가 두 개 이상 있다는 것입니다 . 그러나 항상 인덱스 4의 문자 (5 번째 문자)입니다.

문자열 예 : crt/r2002_2

내가 원하는 것 : crt/2002_2

이 교체 기능은 모두 제거 r

mystring.replace(/r/g, '')

생산 : ct/2002_2

나는이 기능을 시도했다 :

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')

다른 문자로 바꾸면 작동합니다. 단순히 제거하지는 않습니다.

이견있는 사람?


var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');

/r/사용하여 대체 String.prototype.replace합니다.

또는 정규식을 전역 플래그와 함께 사용하여 ( 아래 Erik Reppen & Sagar Gala가 제안한 대로) 모든 발생을

mystring = mystring.replace(/\/r/g, '/');

편집 : 모든 사람들이 여기에서 너무 재미 있고 user1293504 가 명확한 질문에 대답하기 위해 곧 돌아올 것 같지 않으므로 문자열에서 N 번째 문자를 제거하는 방법이 있습니다.

String.prototype.removeCharAt = function (i) {
    var tmp = this.split(''); // convert to an array
    tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
    return tmp.join(''); // reconstruct the string
}

console.log("crt/r2002_2".removeCharAt(4));

user1293504는 인덱스가없는 카운트 대신 일반 카운트를 사용했기 때문에 인덱스에서 1을 제거 charAt해야 tmp.splice(i, 1)합니다. 이를 사용하여 3 번째 행의 인덱스에서 1을 빼지 않고 대신 사용 하는 방법을 복제하려면이를 사용하십시오 .


간단한 기능적인 자바 스크립트 방식은

mystring = mystring.split('/r').join('/')

간단하고 빠르며 전 세계를 대체하며 기능이나 프로토 타입이 필요 없습니다.


항상 네 번째 문자를 제거한다는 것을 알고 있다면 항상 문자열 함수가 있습니다.

str.slice(0, 4) + str.slice(5, str.length))

첫 번째 기능은 거의 옳습니다. 'global'(편집)을 나타내는 'g'플래그를 제거하고 두 번째 'r'을 발견 할 수있는 컨텍스트를 제공하십시오.

편집 : 그것이 '/'를 추가하기 전에 두 번째 'r'인 것을 보지 못했습니다. regEx 인수를 사용할 때 '/'를 이스케이프하려면 \ /가 필요합니다. upvotes에 감사하지만 잘못되었으므로 regEx의 기본 사항을 더 잘 이해하는 데 관심이있는 사람들을 위해 세부 정보를 수정하고 추가 할 것입니다.

mystring.replace(/\/r/, '/')

과도한 설명이 필요합니다 :

regEx 패턴을 읽거나 쓸 때 <문자 또는 문자 집합>과 <문자 또는 문자 집합>, <...

정규식에서 <문자 또는 문자 집합>은 한 번에 하나씩 일 수 있습니다.

/each char in this pattern/

따라서 e, a, c 등을 읽으십시오.

또는 단일 <문자 또는 문자 집합>은 문자 클래스로 설명되는 문자 일 수 있습니다.

/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)

또는 많은 문자와 일치하도록 확장되었습니다 (그러나 순차적 패턴의 관점에서 단일 요소로 생각하는 것이 가장 좋습니다).

/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would

/[aA]{1,3}/
//1-3 matches of 'a' or 'A'

/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class

/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)

따라서 무리를 함께 스무시하십시오.

   var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
   var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can   eat098765';

   joesStr.match(rePattern);

   //returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
   //without the 'g' after the closing '/' it would just stop at the first   match and return:
   //["aaaAAAaaEat at Joes123454321"]

그리고 물론 과도하게 설명했지만 내 요점은 간단히 다음과 같습니다.

/cat/

일련의 3 가지 패턴 요소 (물건 뒤에 물건이옵니다).

그리고 이것도 :

/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/

regEx가 엉뚱 해 보일 때마다 일련의 것들 (잠재적으로 다중 문자 일)로 차례로 나뉩니다. 일종의 기본 요점이지만 과거에 시간이 걸리기 때문에 여기에서 설명을 진행했습니다 .regEx를 처음 접하는 OP 및 다른 사람들이 무슨 일이 일어나고 있는지 이해하는 데 도움이 될 것이라고 생각합니다. 정규식 읽기 / 쓰기의 핵심은이를 여러 부분으로 나누는 것입니다.


'/ r'의 전역 대체를 위해이 코드가 효과적이었습니다.

mystring = mystring.replace(/\/r/g,'');

그냥 고쳐 replaceAt:

String.prototype.replaceAt = function(index, charcount) {
  return this.substr(0, index) + this.substr(index + charcount);
}

mystring.replaceAt(4, 1);

removeAt대신에 전화하겠습니다 . :)


return this.substr(0, index) + char + this.substr(index + char.length);

char.length0입니다. 1이 경우 문자를 건너 뛰 려면 추가해야합니다 .


그것이 yourString에서 항상 네 번째 문자라면 시도해 볼 수 있습니다.

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });

다른 문자로 바꾸면 작동합니다. 단순히 제거하지는 않습니다.

이것은 언제 char 동일합니다 "", char.length당신의 문자열이 원래 문자열을 형성하기 위해 결합하므로, 0입니다. 코드 시도와 함께 다음이 작동합니다.

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + 1);
    //   this will 'replace' the character at index with char ^
}

아래와 같은 기능 생성

  String.prototype.replaceAt = function (index, char) {
      if(char=='') {
          return this.slice(0,index)+this.substr(index+1 + char.length);
      } else {
          return this.substr(0, index) + char + this.substr(index + char.length);
      }
  }

아래와 같이 문자를 바꾸려면

  var a="12346";
  a.replaceAt(4,'5');

여기에 이미지 설명을 입력하십시오

명확한 색인에서 문자를 제거하려면 두 번째 매개 변수를 빈 문자열로 지정하십시오.

a.replaceAt(4,'');

여기에 이미지 설명을 입력하십시오


바꾸기 기능을 사용하여 문자열에서 문자를 제거하는 것을 좋아하지 않습니다. 그렇게하는 것이 논리적이지 않습니다 . 일반적으로 C # (Sharp)으로 프로그래밍하고 문자열에서 문자를 제거 할 때마다 String 클래스의 Remove 메서드를 사용하지만 Replace 메서드는 존재하지만 제거하려고 할 때 제거하기 때문에 제거합니다. 교체하지 마십시오. 이것은 논리적입니다!

Javascript에는 문자열에 대한 제거 기능이 없지만 substr 기능이 있습니다. substr 함수를 한두 번 사용하여 문자열에서 문자를 제거 할 수 있습니다. c # 메서드가 처음으로 String.Remove (int startIndex)를 오버로드하는 것처럼 시작 인덱스에서 문자열 끝까지 문자를 제거하도록 다음 함수를 만들 수 있습니다.

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

그리고 / 또는 c # 메서드의 두 번째 오버로드 String.Remove (int startIndex, int count)와 같이 시작 인덱스 및 카운트에서 문자를 제거하기 위해 다음 함수를 만들 수 있습니다.

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

그런 다음이 두 기능 또는 그 중 하나를 필요에 따라 사용할 수 있습니다!

예:

alert(Remove("crt/r2002_2", 4, 1));

출력 : crt / 2002_2

논리없는 기술을 사용하여 목표 달성 하면 대규모 프로젝트에서이 작업을 많이 수행하면 코드를 이해하는 데 혼란이 생길 ​​수 있으며 향후 실수가 발생할 수 있습니다!


다음 기능은 내 경우에 가장 효과적이었습니다.

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}

가장 짧은 방법은 스플 라이스를 사용하는 것입니다

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);

이것을 사용할 수 있습니다 : if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)

설명:

  1. if ( str[4] === 'r' )
    5 번째 문자가 'r'

  2. str.slice(0, 4)
    전에 모든 것을 얻기 위해 문자열을 슬라이스 'r'

  3. + str.slice(5)
    나머지 문자열을 추가하십시오.

축소 : s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 바이트!]

데모 :

function remove5thR (s) {
  s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
  console.log(s); // log output
}

remove5thR('crt/r2002_2')  // > 'crt/2002_2'
remove5thR('crt|r2002_2')  // > 'crt|2002_2'
remove5thR('rrrrr')        // > 'rrrr'
remove5thR('RRRRR')        // > 'RRRRR' (no change)


단일 문자 만 제거하려는 경우 제거하려는 문자의 색인을 알고있는 경우 다음 기능을 사용할 수 있습니다.

/**
 * Remove single character at particular index from string
 * @param {*} index index of character you want to remove
 * @param {*} str string from which character should be removed
 */
function removeCharAtIndex(index, str) {
    return str.substring(0, index - 1) + str.substring(index, str.length)
}

이것은 simpleigh 응답 (길이 생략)의 개선입니다

s.slice(0,4)+s.slice(5)

let s="crt/r2002_2";

let o= s.slice(0,4)+s.slice(5);

let delAtIdx= (s,i) => s.slice(0,i)+s.slice(i+1); // this function remove letter at index i

console.log(o);
console.log(delAtIdx(s,4));


C # (샤프)에서는 빈 문자를 '\ 0'으로 만들 수 있습니다. 아마도 당신은 이것을 할 수 있습니다 :

String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')

Google에서 검색하거나 간헐적 인 서핑을하고 C #처럼 자바 스크립트를 사용하여 빈 문자를 만들 수 있는지 확인하십시오. 그렇다면, 그것을하는 방법을 배우십시오. 아마도 replaceAt 함수가 작동하여 원하는 것을 얻을 수 있습니다!

마지막으로 'r'문자가 제거됩니다!

참고 URL : https://stackoverflow.com/questions/9932957/how-can-i-remove-a-character-from-a-string-using-javascript

반응형