简体   繁体   English

如何使用正则表达式和Javascript获取字符串的第一个和最后一个字符

[英]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.

相关问题 javascript - 搜索(正则表达式),获取匹配字符串最后一个字符的 position - javascript - search(regex), get position of the last character of the matched string 如何使用JavaScript从字符串中获取前8个字符和最后8个字符? - How to get first 8 char and last 8 char from string using JavaScript? javascript 正则表达式检查第一个和最后一个字符是否相似? - javascript regex to check if first and last character are similar? JavaScript RegEx-替换字符的第一个和最后一个出现 - JavaScript RegEx - replace first and last occurrence of a character Javascript:获取字符串中第一个特殊正则表达式字符的索引 - Javascript: Get index of first special regex character in a string 如何通过 Jquery 或 javaScript 获取字符串的第一个字符? - How to get first character of string by Jquery or javaScript? 如何在JavaScript正则表达式/对象错误中获取字符串的数字的第一个实例到最后一个实例? - How to get first instance to last instance of a number in a string in javascript regex/ object error? javascript正则表达式提取最后指定字符后的第一个字符 - javascript regex to extract the first character after the last specified character 使用正则表达式替换匹配字符串的最后一个字符 - Replace last character of a matched string using regex 如果字符串javascript的最后一个字符如何摆脱? - How do I get rid if the last character of a string javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM