2012-12-22 1 views

답변

2

당신이 문자열이 . 또는 #로 시작하고 다음과 같이 String.match()를 사용할 수는 남아 사용하는 경우 알고 싶은 경우 : 더 나은입니다

if (matches = $string.match(/^([.#])(.+)/)) { 
    // matches[1] will contain either . or # 
    alert(matches[2]); 
} else { 
    // it's something else 
} 
2

단지 정규식을 사용하지 왜, 당신은이 클래스 또는 ID가 당신이 원하는 완전히 무엇

$string.replace(/^(\.|#)/,'') // will replace .class to class - #class to class 

http://jsfiddle.net/FcM2Y/

+0

'(/^(. | #) /'대신에 문자를 제거하고 싶다면)'.element.myclass'는 무엇을 반환해야합니까? – h2ooooooo

+0

' 'dots are most chars'.replace /(.|#)/, '') // "대부분의 문자와 일치합니다" –

+0

답변 해 주셔서 감사합니다! :-) – laukok

2

확실하지 있다면 걱정할 필요가 없습니다 , 개체를 사용하여 찾은 것에 따라 사전 정의 된 설정을 선택할 수 있습니다 (예 :

var $string = ".isclass"; 

var dict = { 
    '.' : 'class', 
    '#' : 'id' 

}, out; 
if ($string[0] in dict) out = dict[$string[0]] + ', ' + $string.slice(1); 
else out = 'no match, ' + $string; 
console.log(out); // "class, isclass" 
+0

대답 해 주셔서 감사합니다! :-) – laukok

+1

@lauthiamkok [jsperf] (http://jsperf.com/object-vs-regex-1-char) 객체에서'in' 연산자를 표시하고'.slice (1)'이 regexp보다 빠릅니다. –