[英]how to get the first and the last character of a string using a Regex and Javascript
I need to get the first and the last letter of a string, using a regex in Javascript and I have no Idea how to achieve this. 我需要使用Javascript中的正则表达式获取字符串的第一个和最后一个字母,我不知道如何实现此目的。 Anyone has an Idea?
有人有主意吗?
As the comments indicate, it would be very simple to do it without regexp: 如注释所示,如果没有regexp,则将非常简单:
var str = "This is my string";
var first = str[0];
var last = str[str.length-1];
If you really need to use a regexp, you could do it like this: 如果您确实需要使用正则表达式,可以这样做:
var matches = str.match(/^.|.$/g); // ["T", "g"]
Just treat the string as an array: 只需将字符串视为数组即可:
text = 'this is a string, hi!';
firstChar = text[0];
lastChar = text[text.length-1];
if you need regex only : 如果只需要正则表达式:
var matches = 'abcde'.match(/^(.).*(.)$/)
console.log(matches)
["abcde", "a", "e"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.