简体   繁体   English

忽略字符串的第一个字符-JS-正则表达式

[英]Ignore first character of string - JS - Regex

I'm trying to write a Regex that will ignore the first character of a string and start with the second character. 我正在尝试编写一个正则表达式,它将忽略字符串的第一个字符并从第二个字符开始。

eg 例如

str = "14";
test = "4";

This will match ONLY if 4 is is position 2 (end of the string) and NOT at the start, the following will fail 只有在位置2(字符串的末尾)是4而不是开头时,这才匹配,以下将失败

str = "21";
test = "4";

I'm rubbish at Regex and all the options I've tried so far haven't worked. 我在Regex上很垃圾,到目前为止我尝试过的所有选项都没有用。

My current code is like so 我当前的代码是这样的

filters = filters.replace(/,\s*$/, '');
objRegex = new RegExp('\\/^.{1}(.*)/' + filters, 'gi');

Where filters is a random string consisting of two characters. 其中过滤器是由两个字符组成的随机字符串。 The current Regex was copied from another SO post but it doesn't work and given my limited knowledge I'm not sure how to make it work, anyone able to help? 当前的Regex是从另一个SO帖子复制而来的,但是它不起作用,并且由于我的知识有限,我不确定如何使它起作用,有谁能够提供帮助?

Thanks! 谢谢!

I think a Regex is a bit overkill, how about something like this: 我认为Regex有点矫kill过正,例如:

var stringToSearch = '14';
var stringToFind = '4';
if (stringToSearch && stringToSearch.length === 2 &&
    stringToSearch[1] === stringToFind) {
    // do something
}

Just use substring method ? 只是使用子串方法?

str = "14";
test = "4";
var str = str.substring(0, 2);

使用以下模式:“ ^ [\\ w] {1} 4 $”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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