program story

JavaScript에서 문자열 이스케이프

inputbox 2020. 11. 29. 10:26
반응형

JavaScript에서 문자열 이스케이프


JavaScript에는 문자열에서 이스케이프해야하는 문자에 백 슬래시를 추가하는 PHP addslashes(또는 addcslashes) 함수 와 같은 내장 함수가 있습니까?

예를 들면 다음과 같습니다.

이것은 '작은 따옴표'와 '큰 따옴표'가있는 데모 문자열입니다.

...이 될 것입니다 :

이것은 \ '작은 따옴표 \'와 \ "큰 따옴표 \"가있는 데모 문자열입니다.


http://locutus.io/php/strings/addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

큰 따옴표에 대해 이것을 시도 할 수도 있습니다.

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);

String에서 직접 작동 하는 Paolo Bergantino제공하는 기능의 변형 :

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

위의 코드를 라이브러리에 추가하면 다음을 수행 할 수 있습니다.

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

편집하다:

주석의 제안에 따라 JavaScript 라이브러리 간의 충돌이 우려되는 사람은 다음 코드를 추가 할 수 있습니다.

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

encodeURI () 사용

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

웹 애플리케이션에서 사용하기 위해 적절한 JSON 인코딩 및 전송을 위해 문자열에서 거의 모든 문제가있는 문자를 이스케이프합니다. 완벽한 검증 솔루션은 아니지만 간단하게 수행 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/770523/escaping-strings-in-javascript

반응형