source

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

factcode 2022. 11. 16. 21: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','/');

will will를 /r/를 사용합니다.

또는 글로벌플래그(아래 Erik Reppen & Sagar Gala에서 권장하는 바와 같이)와 함께 regex를 사용하여 모든 발생을 다음과 같이 대체할 수 있습니다.

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

편집: 모두가 매우 즐거워하고 있으며 사용자 1293504가 명확한 질문에 답하기 위해 바로 돌아올 것 같지 않기 때문에 문자열에서 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를 사용하여 user1293504를 사용하는 방법을 1을 해야 합니다.이것을 사용하여 다음 방법을 재현하려면charAt은 세 을 빼지 저작물을 사용합니다.tmp.splice(i, 1)★★★★★★ 。

javascript의 간단한 기능 방법은 다음과 같습니다.

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

단순하고 빠르며 전 세계적으로 대체되며 기능이나 프로토타입이 필요하지 않습니다.

항상 네 번째 문자를 제거할 경우 문자열 함수가 있습니다.

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

네 첫 번째 펑크가 거의 맞아.'global'(편집)을 나타내는 'g' 플래그를 제거하고 두 번째 'r'을 찾을 수 있는 컨텍스트를 지정합니다.

편집: 이전 두 번째 'r'인 것을 알 수 없으므로 '/'을(를) 추가했습니다.regEx arg를 사용할 때 '/'을(를) 이스케이프하려면 \/가 필요합니다.조언해 주셔서 감사합니다만, 제가 틀렸기 때문에 regEx의 기본에 대해 더 잘 이해하고자 하는 분들을 위해 수정하고 자세한 내용을 덧붙이겠습니다만, 이 방법은 도움이 될 것입니다.

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

자세한 설명은 다음과 같습니다.

regEx 패턴을 읽고 쓸 때 다음과 같이 생각하십시오.<문자 또는 문자 세트>,<문자 또는 문자 세트>,<...

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가 보기 시작하면 모든 것이 연속적으로 이어지는 일련의 것(잠재적으로 다중 문자일 가능성이 있음)으로 귀결됩니다.기본적인 요점이긴 하지만 지나치는 데 시간이 좀 걸려서 여기서 설명하는 것은 OP나 regEx를 처음 접하는 사람들에게 무슨 일이 일어나고 있는지 이해시키는 데 도움이 될 것 같아서 무리하게 설명했습니다.regEx를 읽고 쓰기 위한 열쇠는 그것을 여러 조각으로 나누는 것입니다.

고쳐주세요.replaceAt:

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

mystring.replaceAt(4, 1);

는 그것을 고고라고 부르고 .removeAt신신: : )

'/r'을(를) 전역으로 대체하기 위해 이 코드를 사용할 수 있었습니다.

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

이것은 심플한 답변의 개선입니다(간단한 길이).

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

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

char.length0이 . 때 더해야 요.1이 경우 문자를 건너뜁니다.

let str = '1234567';
let index = 3;
str = str.substring(0, index) + str.substring(index + 1);
console.log(str) // 123567 - number "4" under index "3" is removed

내가 얼간이인지도 모르지만 오늘 우연히 이런 걸 봤는데 불필요하게 복잡한 것 같아.

여기 끈에서 원하는 것을 제거하는 더 간단한 방법이 있습니다.

function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']

for (let char of forbiddenChars){
    input = input.split(char).join('');
}
return input

}

다음과 같은 함수를 만듭니다.

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

여기에 이미지 설명 입력

항상 yourString의 네 번째 글자인 경우 다음을 시도할 수 있습니다.

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

다른 캐릭터로 대체해야만 작동합니다.그것은 단순히 그것을 제거하지 않을 것이다.

는 this this this this가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 ^
}

쓸 수 요.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) {
    var maxIndex=index==0?0:index;
    return str.substring(0, maxIndex) + str.substring(index, str.length)
}

문자열에서 문자를 제거하는 치환 기능을 사용하는 것을 싫어합니다.그렇게 하는 것은 논리적이지 않다.보통 C#(Sharp)에서 프로그램을 하는데 문자열에서 문자를 삭제할 때는 항상 String 클래스의 Remove 메서드를 사용합니다.하지만 Replace 메서드는 사용하지 않습니다.이는 삭제하려고 할 때 삭제하기 때문에 치환하지 않습니다.논리적이네요!

Javascript에서는 문자열 제거 기능은 없지만 기판 기능은 있습니다.기판 함수를 한두 번 사용하여 문자열에서 문자를 제거할 수 있습니다.c# 메서드 first overload String과 마찬가지로 시작 인덱스에서 문자열 끝까지 문자를 삭제하는 함수를 만들 수 있습니다.삭제(인트 스타트)인덱스):

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

또한 c# 메서드의 second overload String과 마찬가지로 시작 인덱스와 카운트 시 다음 함수를 사용하여 문자를 제거할 수도 있습니다.삭제(인트 스타트)인덱스, int 카운트):

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

이 문제에는 많은 응용 프로그램이 있습니다.복사/붙여넣기 쉬운 @simpleigh 솔루션 조정:

function removeAt( str1, idx) {
  return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1))  // prints: abcdef

다른 방법은 기본적으로 다음과 같습니다.

  1. 다음 명령을 사용하여 문자열을 배열로 변환Array.from()방법.
  2. 어레이를 루프하여 모두 삭제r색인 1을 가진 문자를 제외하고.
  3. 어레이를 문자열로 변환합니다.

let arr = Array.from("crt/r2002_2");

arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });

document.write(arr.join(""));

[인덱스] 위치를 사용하여 특정 문자 제거

String.prototype.remplaceAt = function (index, distance) {
  return this.slice(0, index) + this.slice(index + distance, this.length);
};

https://stackoverflow.com/users/62576/ken-white에 크레딧을 기입해 주세요.

C#(샤프)에서는 빈 문자를 '\0'으로 만들 수 있습니다.다음과 같이 할 수 있습니다.

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

구글에서 검색하거나 인터넷에서 서핑하여 Javascript가 C#처럼 빈 문자를 만들 수 있는지 확인합니다.그렇다면 방법을 배우면 replaceAt 기능이 마침내 작동하여 원하는 것을 달성할 수 있을 것입니다.

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

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

반응형