简体   繁体   中英

Get specific letters between two symbols

I'm trying to get the letters between two specified symbols.

Example

var a = 'Testing code https://example.com/ABC-BAC tralala';  // I would need to get ABC
var b = 'Depends on x \n https://example.com/CADER-BAC';  // I would need to get CADER
var c ='lots of examples: \n example.com/CAB-BAC'; // I would need to get CAB

var d ='lots of examples: \n https://abc.example.com/CAB-BAC'; // I would need to get CAB

My main problem is that I need a unique syntax that would work for both https:// version or without any https://, therefore using indexOf on '/' wouldn't work that well.

I've tried regex but of course, that only fits one solution:

 let regex = /^https://example\.com/[a-zA-Z]+-BAC$/i;
 return regex.test(input);

Any help is appreciated, thank you!

You may use match here:

 var input = "https://example.com/CADER-BAC"; var code = input.match(/^.*\/([^-]+)-.*$/); console.log(code[1]);

You can use str.substring in combination of str.lastIndexOf :

 const a = 'Testing code https://example.com/ABC-BAC tralala'; // I would need to get ABC const b = 'Depends on x \n https://example.com/CADER-BAC'; // I would need to get CADER const c = 'lots of examples: \n example.com/CAB-BAC'; // I would need to get CAB const getSubstring = (str) => { return str.substring( str.lastIndexOf('example.com/') + 'example.com/'.length, str.lastIndexOf('-')) } console.log(getSubstring(a), getSubstring(b), getSubstring(c))

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