在javascript中从字符串中拆分数字(仅ID)

在javascript中从字符串中拆分数字(仅ID),javascript,regex,split,Javascript,Regex,Split,我想把“Sachin Tendulkar(123456)”拆分为 在少数情况下,我有“320Gangadar街区(MD)(122435)” 我需要分开括号内的数字和名称, 我尝试过.split(/(\d+/),但在“320Gangadar区块(MD)(122435)”中失败 预期结果: Name = "320Gangadar Block(MD)" ID = "122435" 最好在字符串上使用lastIndexOf函数,如下所示: const str=“320Gangadar区块(MD)(1

我想把“Sachin Tendulkar(123456)”拆分为

在少数情况下,我有“320Gangadar街区(MD)(122435)”

我需要分开括号内的数字和名称, 我尝试过
.split(/(\d+/)
,但在“320Gangadar区块(MD)(122435)”中失败

预期结果:

Name = "320Gangadar Block(MD)"
ID = "122435"

最好在字符串上使用lastIndexOf函数,如下所示:

const str=“320Gangadar区块(MD)(122435)”;
const idStart=str.lastIndexOf(“”);
const name=str.substring(0,idStart);
const id=str.substring(idStart+1,str.length-1);
document.getElementById(“名称”).innerText=“名称:”+名称;
document.getElementById(“id”).innerText=“id:”+id;


在正则表达式中,有一些保留字符具有特殊含义。
()
就是其中之一。要使用
或任何其他特殊字符,请使用
\
对其进行转义

您可以使用
string.prototype.match
id
。您需要匹配
()
为此,正则表达式将是

/\(\d+\)/
使用slice删除编号周围的
()

使用
split()
对于同一个正则表达式,您将得到数字前面的所有字母,如
name

函数拆分(str){
让[id]=str.match(/\(\d+\)/)
让[name]=str.split(/\(\d+\)/)
return[name.trim(),id.slice(1,-1)]
}

log(split(“Sachin Tendulkar(123456)”)
您可以使用正则表达式检索
(id)
,然后从第一个文本检索id

函数getNameId(文本){ 常量regex=/\(\d+\)/g; const[id]=text.match(regex); const userId=id.slice(1,id.length-1); const name=text.slice(0,text.indexOf(id)).trim(); 返回{ 名称 id:userId } } 日志(getNameId(“Sachin Tendulkar(123456)”)
console.log(getNameId(“320Gangadar块(MD)(122435)”)
不要拆分?尝试改用
match
?不要忘了需要在regexp中转义
()
,以逐字匹配它们。
Name.match(/\(\d+)/)[1]
将为您提供ID
“320Gangadar块(MD)(122435)”.match(/^(.*)(\d+)$/)谢谢你的回答,但是你可以随时欢迎你的评论吗?也可以考虑把你的代码块转换成一个“堆栈片段”。@ EngRexbox我已经编辑了我的答案,谢谢你的反馈。欢迎你。我假设下投票与实际答案不一致,而不是格式化。
/\(\d+\)/