JavaScript에서 문자열을 어떻게 트리밍합니까? 즉, JavaScript에서 문자열의 시작과 끝에서 모든 공백을 어떻게 제거합니까?
질문자 :Vinod
IE9+ 이후의 모든 브라우저에는 trim()
메서드가 있습니다.
" \n test \n ".trim(); // returns "test" here
trim()
지원하지 않는 브라우저의 경우 MDN 에서 이 폴리필을 사용할 수 있습니다.
if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); }
jQuery
사용하는 경우 $.trim(str)
도 사용할 수 있으며 undefined/null을 처리합니다.
이것 좀 봐:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');}; String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}; String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}; String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Pradeep Kumar Mishra
이미 해당 프레임워크를 사용하고 있다면 jQuery 의 트림이 편리합니다.
$.trim(' your string ');
나는 jQuery를 자주 사용하는 경향이 있으므로 그것을 사용하여 문자열을 트리밍하는 것이 나에게는 자연스럽습니다. 그러나 jQuery에 대한 반발이 있을 수 있습니까? :)
barneytron
위에 많은 정답이 있지만 JavaScript String
객체에는 ECMAScript 5 .trim()
메서드가 있다는 점에 유의해야 합니다. 따라서 이상적으로는 트림 방법을 프로토타입하려는 모든 시도는 실제로 그것이 이미 존재하는지 먼저 확인해야 합니다.
if(!String.prototype.trim){ String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,''); }; }
기본적으로 추가: JavaScript 1.8.1 / ECMAScript 5
따라서 다음에서 지원됩니다.
파이어폭스: 3.5+
사파리: 5+
Internet Explorer: IE9+ (표준 모드에서만!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more .aspx
크롬: 5+
오페라: 10.5+
ECMAScript 5 지원 테이블: http://kangax.github.com/es5-compat-table/
scunliffe
사용할 수 있는 구현이 많이 있습니다. 가장 분명한 것은 다음과 같습니다.
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); }; " foo bar ".trim(); // "foo bar"
Gumbo
간단한 버전 여기 JavaScript 트림의 일반 기능은 무엇입니까?
function trim(str) { return str.replace(/^\s+|\s+$/g,""); }
Mark Davidson
이 질문이 3년 전에 제기되었다는 것을 알고 있습니다. 이제 String.trim()
이 JavaScript에 기본적으로 추가되었습니다. 예를 들어 다음과 같이 직접 트리밍할 수 있습니다.
document.getElementById("id").value.trim();
Vijin Paulraj
jQuery를 사용하는 경우 jQuery.trim()
함수를 사용하십시오. 예를 들어:
if( jQuery.trim(StringVariable) == '')
Able Alias
Flagrant Badassery 에는 벤치마크 정보가 포함된 11가지 트림이 있습니다.
http://blog.stevenlevithan.com/archives/faster-trim-javascript
당연히 regexp 기반은 기존 루프보다 느립니다.
여기 내 개인이 있습니다. 이 코드는 오래되었습니다! JavaScript1.1 및 Netscape 3용으로 작성했으며 그 이후로 약간만 업데이트되었습니다. (원래 사용된 String.charAt)
/** * Trim string. Actually trims all control characters. * Ignores fancy Unicode spaces. Forces to string. */ function trim(str) { str = str.toString(); var begin = 0; var end = str.length - 1; while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; } while (end > begin && str.charCodeAt(end) < 33) { --end; } return str.substr(begin, end - begin + 1); }
Tero
기본 JavaScript 메서드인 String.trimLeft()
, String.trimRight()
및 String.trim()
합니다.
String.trim()
은 IE9+ 및 기타 모든 주요 브라우저 에서 지원됩니다.
' Hello '.trim() //-> 'Hello'
String.trimLeft()
및 String.trimRight()
는 비표준이지만 IE를 제외한 모든 주요 브라우저 에서 지원됩니다.
' Hello '.trimLeft() //-> 'Hello ' ' Hello '.trimRight() //-> ' Hello'
그러나 폴리필을 사용하면 IE 지원이 쉽습니다.
if (!''.trimLeft) { String.prototype.trimLeft = function() { return this.replace(/^\s+/,''); }; String.prototype.trimRight = function() { return this.replace(/\s+$/,''); }; if (!''.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } }
Web_Designer
String.prototype.trim = String.prototype.trim || function () { return this.replace(/^\s+|\s+$/g, ""); }; String.prototype.trimLeft = String.prototype.trimLeft || function () { return this.replace(/^\s+/, ""); }; String.prototype.trimRight = String.prototype.trimRight || function () { return this.replace(/\s+$/, ""); }; String.prototype.trimFull = String.prototype.trimFull || function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " "); };
Matt Duereg 에게서 뻔뻔스럽게 도난당했습니다.
yckart
Angular js 프로젝트에서 코드 자르기
var trim = (function() { // if a reference is a `String`. function isString(value){ return typeof value == 'string'; } // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; }; } return function(value) { return isString(value) ? value.trim() : value; }; })();
trim(" hello ")
이라고 부릅니다.
rab
단순히 코드를 사용
var str = " Hello World! "; alert(str.trim());
브라우저 지원
Feature Chrome Firefox Internet Explorer Opera Safari Edge Basic support (Yes) 3.5 9 10.5 5 ?
이전 브라우저의 경우 프로토타입 추가
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; }
Behnam Mohammadi
다음은 매우 간단한 방법입니다.
function removeSpaces(string){ return string.split(' ').join(''); }
HenryDev
trim을 사용하는 lib가 있습니다. 그래서 다음 코드를 사용하여 해결했습니다.
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
Zesar
일반 JavaScript를 사용하여 수행할 수 있습니다.
function trimString(str, maxLen) { if (str.length <= maxLen) { return str; } var trimmed = str.substr(0, maxLen); return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…'; } // Let's test it sentenceOne = "too short"; sentencetwo = "more than the max length"; console.log(trimString(sentenceOne, 15)); console.log(trimString(sentencetwo, 15));
user5846985
여기에 어떤 버그가 숨길 수 있는지 모르지만 이것을 사용합니다.
var some_string_with_extra_spaces=" goes here " console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
또는 텍스트가 포함된 경우 다음이 입력됩니다.
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
또 다른 시도:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
plavozont
다음은 TypeScript에 있습니다.
var trim: (input: string) => string = String.prototype.trim ? ((input: string) : string => { return (input || "").trim(); }) : ((input: string) : string => { return (input || "").replace(/^\s+|\s+$/g,""); })
네이티브 프로토타입을 사용할 수 없는 경우 정규식으로 대체됩니다.
Joseph Lennox
나는 2008년에 JS 방식으로 .trim() 함수를 사용할 수 없었을 때 trim을 위해 이 함수를 작성했습니다. 일부 구형 브라우저는 여전히 .trim() 함수를 지원하지 않으며 이 함수가 누군가를 도울 수 있기를 바랍니다.
트림 기능
Community Wiki
광산은 단일 정규식을 사용하여 트리밍이 필요한 경우를 찾고 해당 정규식의 결과를 사용하여 원하는 하위 문자열 범위를 결정합니다.
var illmatch= /^(\s*)(?:.*?)(\s*)$/ function strip(me){ var match= illmatch.exec(me) if(match && (match[1].length || match[2].length)){ me= me.substring(match[1].length, p.length-match[2].length) } return me }
여기에 들어간 한 가지 디자인 결정은 하위 문자열을 사용하여 최종 캡처를 수행하는 것이었습니다. s/\?:// (중간 기간 캡처 만들기) 및 대체 조각은 다음과 같습니다.
if(match && (match[1].length || match[3].length)){ me= match[2] }
이 impls에는 두 가지 성능 베팅이 있습니다.
부분 문자열 구현은 원래 문자열의 데이터를 복사합니까? 그렇다면 첫 번째에서 문자열을 트리밍해야 할 때 이중 순회가 있습니다. 첫 번째는 정규식(부분적일 수 있음)이고 두 번째는 부분 문자열 추출입니다. 하위 문자열 구현은 원래 문자열만 참조하므로 하위 문자열과 같은 작업은 거의 무료일 수 있습니다. 교차 손가락
정규식 impl에서 캡처가 얼마나 좋은가요? 중간 기간인 출력 값은 잠재적으로 매우 길 수 있습니다. 나는 모든 정규식 impls' 캡처가 몇 백 KB 입력 캡처를 방해하지 않을 것이라고 은행에 저장할 준비가 되지 않았지만 테스트도 하지 않았습니다(너무 많은 런타임, 죄송합니다!). 두 번째는 항상 캡처를 실행합니다. 엔진이 히트를 치지 않고 이 작업을 수행할 수 있다면 아마도 위의 스트링 로핑 기술 중 일부를 사용하여 확실히 사용하십시오!
rektide
IE9+ 및 기타 브라우저의 경우
function trim(text) { return (text == null) ? '' : ''.trim.call(text); }
Codler
출처 : http:www.stackoverflow.com/questions/498970/trim-string-in-javascript
'etc. > StackOverFlow' 카테고리의 다른 글
내 스크립트를 실행하는 Python 버전을 어떻게 확인합니까? (0) | 2023.04.14 |
---|---|
Bitmap 개체에 이미지를 로드하는 동안 이상한 OutOfMemory 문제 (0) | 2023.04.14 |
HashMap을 직접 초기화하는 방법(문자 그대로)? (0) | 2023.04.14 |
텍스트 상자의 Enter 키에서 JavaScript로 버튼 클릭 트리거 (0) | 2023.04.14 |
Git 태그의 이름을 어떻게 바꾸나요? (0) | 2023.04.14 |