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

JavaScript로 문자열 내부의 모든 문자를 바꾸는 방법

정규식(RegEx) 및 replace()를 사용하여 (문자열) 안의 문자를 JavaScript로 바꾸는 방법 알아보기 방법.

텍스트 블록이 있고 엠 대시를 사용하려고 한다고 가정해 보겠습니다. (—), 하지만 실수로 하이픈을 사용했습니다. (-):

const textBlock =
  "When you’re typing fast it’s normal to make a few spelling mistakes here and there - it just means you’re human."

다행히 정규 표현식과 replace()를 사용하여 JavaScript로 이 문제를 해결할 수 있습니다. 방법:

const textBlockCorrected = textBlock.replace(/-/g, "—")

console.log(textBlockCorrected)
// "When you’re typing fast it’s normal to make a few spelling mistakes here and there — it just means you’re human."

똑같이 생겼나요? 저를 믿으세요. 그렇지 않습니다. 자세히 살펴보십시오.또는 textBlock의 결과를 인쇄해 보십시오. 및 textBlockCorrected 차이점을 더 쉽게 확인할 수 있습니다.

console.log(textBlock)
//"When you’re typing fast it’s normal to make a few spelling mistakes here and there - it just means you’re human."

console.log(textBlockCorrected)
// "When you’re typing fast it’s normal to make a few spelling mistakes here and there — it just means you’re human."

참고:타이포그래피에서는 사용된 글꼴이 코드 예제에 사용하는 것과 같은 모노타입이 아닐 때 문자와 기호의 차이를 훨씬 쉽게 구분할 수 있습니다(Menlo ). 하지만 타이포그래피 중심의 튜토리얼을 위해 em, en 및 하이픈에 대한 세부 정보를 저장하겠습니다.