如何选择字符串的最后两个字符

时间:2012-05-24 16:50:49

标签: javascript

我需要从变量中选择最后两个字符,无论是数字还是字母。

例如:

var member = "my name is maanu";

我想在member变量中显示字符串中的最后两个字母。

9 个答案:

答案 0 :(得分:324)

您可以将否定索引传递给.slice()

var member = "my name is maanu";

var last2 = member.slice(-2);

alert(last2); // "nu"

答案 1 :(得分:20)

请尝试此操作,请注意您无需在substring中指定结束索引。

var characters = member.substr(member.length -2);

答案 2 :(得分:6)

以下示例使用带有负索引的slice()



var str = 'my name is maanu.';
console.log(str.slice(-3));     // returns 'nu.' last two
console.log(str.slice(3, -7)); // returns 'name is'
console.log(str.slice(0, -1));  // returns 'my name is maanu'




答案 3 :(得分:5)

你可以尝试

member.substr(member.length-2);

答案 4 :(得分:2)

您应该使用substring而不是jQuery来执行此操作。

尝试这样的事情:

member.substring(member.length - 2, member.length)

W3Schools(非官方,但偶尔也有帮助):http://www.w3schools.com/jsref/jsref_substring.asp

根据评论者的要求添加MDN链接:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

答案 5 :(得分:1)

var member = "my name is maanu";

var answer=member.substring(0,member.length - 2);

alert(answer);

答案 6 :(得分:0)

如果它是一个整数,你需要一部分....

var result = number.toString().slice(-2);

答案 7 :(得分:0)

最短距离:

str.slice(-2)

示例:

const str = "test";
const last2 = str.slice(-2);

console.log(last2);

答案 8 :(得分:0)

切片可用于查找子字符串。当我们知道索引时,我们可以使用替代解决方案,例如索引明智加法器。两者的执行时间大致相同。

const primitiveStringMember = "my name is Mate";

const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object


/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/

//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);


//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);