1

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!

johnnasx
  • 158
  • 10

2 Answers2

1

You may use match here:

var input = "https://example.com/CADER-BAC";
var code = input.match(/^.*\/([^-]+)-.*$/);
console.log(code[1]);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • `input.match(/^.*\/([^-]+)-.*$/);` - and what is this dark, magical string? Bear in mind the OP's statement: "*My knowledge on regex is way too limited for this unfortunately...*" – David Thomas Apr 19 '21 at 11:38
  • The current code works for that simple url but will not work for preceding words or \n before the actual url, please see the edited question. – johnnasx Apr 19 '21 at 11:42
  • I made it work for precending words by removing ^ . Thank you for your initial answer. – johnnasx Apr 19 '21 at 11:46
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))
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34