Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

문자열의 모든 인스턴스를 JavaScript로 바꾸는 방법

정규식(RegEx) 및 replace()를 사용하여 JavaScript에서 단어(문자열)의 모든 인스턴스를 바꾸는 방법 알아보기 방법.

회사의 최신 제품에 대해 이야기하는 방대한 텍스트 블록이 있지만 불행히도 한 단어의 철자가 여러 번 틀리는 경우를 가정해 보겠습니다. 다음 텍스트 블록은 "Glorious Games"가 아니라 "Epic Games"로 표시되어야 했습니다.

const textBlock =
  "We at Glorious Games, are very proud to present the latest edition of the Unreal Tournament series. Glorious Games would like to invite our fans to come over to the Glorious Games stand at E3 in 2021."

다행히 JavaScript를 사용하여 이 문제를 빠르게 해결할 수 있습니다.

const textBlockCorrected = textBlock.replace(/Glorious/g, "Epic")

console.log(textBlockCorrected)
// "We at Epic Games, are very proud to present the latest edition of the Unreal Tournament series. Epic Games would like to invite our fans to come over to the Epic Games stand at E3 in 2021."

예!

코드에서 무슨 일이 일어나고 있습니까?

  • 먼저 textBlockCorrected라는 새 변수를 선언합니다. .
  • 그런 다음 새 변수를 원래 textBlock 값과 동일하게 설정합니다. .
  • 그런 다음 replace()를 첨부합니다. textBlock 메소드 , 다음 정규식의 인수를 지정합니다. /Glorious/g, "Epic" 마법이 일어나는 곳입니다.

g (global) 플래그를 사용하면 텍스트 블록에서 "Glorious"의 모든 인스턴스를 "Epic"으로 바꿀 수 있습니다. g 플래그는 JavaScript에서 문자열에 있는 단어의 여러 인스턴스를 바꾸는 유일한 방법입니다.