如何检查字符串是类还是 ID,然后将它们剥离以获取名称?例如,
$string = ".isclass";
$string = "#isid";
if($($string).indexOf('.') != -1)) alert($($string).substring(1));
如何检查字符串是类还是 ID,然后将它们剥离以获取名称?例如,
$string = ".isclass";
$string = "#isid";
if($($string).indexOf('.') != -1)) alert($($string).substring(1));
为什么不只使用正则表达式,那么您不必担心它是类还是 id
$string.replace(/^(\.|#)/,'') // will replace .class to class - #class to class
如果您想知道字符串是否以.
or开头#
,然后使用剩下的,您可以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"