繁体   English   中英

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

[英]Get specific letters between two symbols

我正在尝试获取两个指定符号之间的字母。

例子

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

我的主要问题是,我需要一种适用于 https:// 版本或没有任何 https:// 的独特语法,因此在“/”上使用 indexOf 不会那么好。

我已经尝试过正则表达式,但当然,这只适合一种解决方案:

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

任何帮助表示赞赏,谢谢!

你可以在这里使用match

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

您可以结合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