Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取两个符号之间的特定字母_Javascript_Regex - Fatal编程技术网

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

Javascript 获取两个符号之间的特定字母,javascript,regex,Javascript,Regex,我正在尝试获取两个指定符号之间的字母 范例 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'; //

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

范例

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不会很好地工作

我尝试过regex,但当然,这只适用于一种解决方案:

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


非常感谢您的帮助,谢谢

您可以在此处使用
match

var输入=”https://example.com/CADER-BAC";
var code=input.match(/^.*\/([^-]+)-.*$/);
console.log(代码[1])您可以结合使用:

const a='测试代码https://example.com/ABC-BAC 特拉拉拉';//我需要上ABC
常数b='取决于x\nhttps://example.com/CADER-BAC'; // 我需要找卡德
const c='大量示例:\n example.com/CAB-BAC';//我需要叫辆出租车
const getSubstring=(str)=>{
返回str.substring(
str.lastIndexOf('example.com/')+'example.com/'.length,
str.lastIndexOf('-'))
}

console.log(getSubstring(a)、getSubstring(b)、getSubstring(c))
你有没有考虑过使用带有匹配项的正则表达式?@Glubus我对正则表达式的了解非常有限,很遗憾,我一开始就试过了,这能回答你的问题吗?这些弦是从哪里来的?它们是否在页面、文本..的
元素中?它们是简单的字符串,而不是html元素。我正在为node.js服务器
input.match(/^.*\/([^-]+)-.*$/)编写一些代码-这条黑色的神奇的线是什么?请记住OP的声明:“我对regex的了解非常有限,很遗憾……”当前代码适用于该简单url,但不适用于前面的单词或实际url之前的单词,请参见编辑后的问题。我通过删除^使其适用于前面的单词。谢谢你的初步答复。