如何检查字符串是类还是ID,然后剥离它们以获得名称



如何检查字符串是类还是ID,然后剥离它们以获得名称?例如,

$string = ".isclass"; 
$string = "#isid";
if($($string).indexOf('.') != -1)) alert($($string).substring(1));

如果您想知道字符串是否以.#开头,然后使用剩余的,您可以使用String.match(),如下所示:

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

不能完全确定你想要什么,但是你可以选择预定义的设置,这取决于你使用一个对象,例如

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"

为什么不直接使用正则表达式呢?这样你就不用担心它是一个类还是一个id

$string.replace(/^(.|#)/,'') // will replace .class to class - #class to class
http://jsfiddle.net/FcM2Y/

最新更新