简体   繁体   中英

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

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

I'm rubbish at Regex and all the options I've tried so far haven't worked.

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?

Thanks!

I think a Regex is a bit overkill, how about something like this:

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 $”

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