如何在 JQuery 中获取字符串的前三个字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15196706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the first three letters of a string in JQuery?
提问by Shah
How can I get the first three letters of a string in JQuery?
如何在 JQuery 中获取字符串的前三个字母?
For example: Turn cat1234 to cat
例如:将 cat1234 转为 cat
回答by X-Factor
No jQuery needed! Just use the substring method:
不需要jQuery!只需使用子字符串方法:
var name = "cat1234"
var variable2 = name.substring(0, 3);
回答by Jai
Use .slice(start, end)
with start and end values:
使用.slice(start, end)
与起点和终点值:
var str = 'cat1234';
document.body.innerHTML = str.slice(0, 3);
With javascript you can use a regular expression with .match()
method to exclude the number and get the string value.
使用javascript,您可以使用带有.match()
方法的正则表达式来排除数字并获取字符串值。
var str ='cat1234',
rg = /[a-zA-Z]+/g,
ns = str.match(rg);
document.body.innerHTML = ns[0];
回答by Sudhir Bastakoti
you could also do:
你也可以这样做:
var str = "cat1234";
console.log( str.substr(0, 3));
回答by kamituel
Use substring():
使用substring():
"cat1234".substring(0,3);
It means "get all the characters starting at position 0 up to position 3".
这意味着“获取从位置 0 开始到位置 3 的所有字符”。
Please note this is not a JQuery function, it's plain Java Script.
请注意,这不是 JQuery 函数,它是普通的 Java 脚本。