[英]Check if first and last character contains given special char
I have input string我有输入字符串
..-----''''''.......VAibhavs.sharma'..'-.'-.''-....''
I want to check if the first and last char place contains -
or '
or .
我想检查第一个和最后一个字符位置是否包含
-
或'
或.
. .
If yes then trim
until we get name.如果是,那么
trim
直到我们得到名字。
Expected output: VAibhavs.sharma
预期 output:
VAibhavs.sharma
I am using like this.我是这样使用的。
while (
myString.charAt(0) == "." ||
myString.charAt(0) == "'" ||
myString.charAt(0) == "-" ||
myString.charAt(myString.length - 1) == "." ||
myString.charAt(myString.length - 1) == "'" ||
myString.charAt(myString.length - 1) == "-"
)
I know this is not correct way.我知道这不是正确的方法。 How can I use regex?
如何使用正则表达式?
I tried /^\'$
.我试过
/^\'$
。 But this only checks or first char for a single special char.但这仅检查单个特殊字符的或第一个字符。
You can use regular expression:您可以使用正则表达式:
input = "..-----''''''.......VAibhavs.sharma'..'-.'-.''-....''"
output = input.replace(/^[-'\.]+/,"").replace(/[-'\.]+$/,"")
console.log(output)
[-'\.]
... -
, '
or .
[-'\.]
... -
, '
或.
character+
... one or more times +
... 一次或多次^
... beginning of the string ^
... 字符串的开头$
... end of the string $
... 字符串结尾EDIT:编辑:
using match
:使用
match
:
input = "..-----''''''.......VAibhavs.sharma'..'-.'-.''-....''"
output = input.match(/^[-'\.]+(.*?)[-'\.]+$/)[1]
console.log(output)
(...)
... (1st) group (...)
...(第 1 组).*?
... any chacter, zero or more times, ?
?
means non-greedy.match(...)[1]
... 1
means 1st group .match(...)[1]
... 1
表示第一组There is already one accepted answer but still, this is how I would do.已经有一个被接受的答案,但我仍然会这样做。
var pattern = /\b[A-Za-z.]+\b/gm;
var str = "..-----''''''.......VAibhavs.sharma'..'-.'-.''-....''";
console.log(str.match(pattern));
// Output
// ["VAibhavs.sharma"]
\b
is a zero-width word boundary. \b
是一个零宽度的单词边界。 It matches positions where one side is a word character (usually a letter, digit or underscore) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).它匹配一侧是单词字符(通常是字母、数字或下划线)而另一侧不是单词字符(例如,它可能是字符串的开头或空格字符)的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.