2

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

$string = ".isclass"; 
$string = "#isid";

if($($string).indexOf('.') != -1)) alert($($string).substring(1));
4

3 回答 3

2

为什么不只使用正则表达式,那么您不必担心它是类还是 id

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

http://jsfiddle.net/FcM2Y/

于 2012-12-22T01:34:10.047 回答
2

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

if (matches = $string.match(/^([.#])(.+)/)) {
    // matches[1] will contain either . or #
    alert(matches[2]);
} else {
    // it's something else
}
于 2012-12-22T02:24:18.457 回答
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"
于 2012-12-22T01:46:03.790 回答