简体   繁体   中英

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. Anyone has an Idea?

As the comments indicate, it would be very simple to do it without 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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM