简体   繁体   English

获取两个符号之间的特定字母

[英]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.我的主要问题是,我需要一种适用于 https:// 版本或没有任何 https:// 的独特语法,因此在“/”上使用 indexOf 不会那么好。

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:你可以在这里使用match

 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 :您可以结合str.lastIndexOf 使用 str.substring

 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))

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

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