我有这样的字符串
var str1 = "EmployeeName1";
str1
可以是"EmployeeName2"
或"EmployeeName3"
或"EmployeeName4"
。
我想在str1
中搜索一个数字(1,2,3,4),并用包含该数字的字符串替换该单个数字,以便
"EmployeeName1" -> "EmployeePosition1"
"EmployeeName2" -> "EmployeePosition2"
"EmployeeName3" -> "EmployeePosition3"
如何访问找到的数字1,2,3并在正则表达式中使用?
之类的东西str1.replace([0-9]/ig, "Position?????")
答案 0 :(得分:0)
我不知道你想要做什么,但要使用正则表达式,你需要做这样的事情
R =正则表达式( '[0-9]');
str1.replace(R, '位置');
答案 1 :(得分:0)
var names=["EmployeeName1","EmployeeName2","EmployeeName3"]
var positions=["EmployeePosition1", "EmployeePosition2", "EmployeePosition3"]
function get(name){
var num=parseInt(name.replace( /^\D+/g, ''))
var pos=positions.map(function(el){return parseInt(el.replace( /^\D+/g, ''))})
return positions[pos.indexOf(num)]
}
console.log( get(names[0]) )