转换字符串值的Javascript方法

时间:2018-11-09 18:28:19

标签: javascript

有人可以帮我写一个采用String值的JS方法吗?
/ Content / blockDiagram / 0 / bundle / 0 / selectedBundle
/ Content / blockDiagram / 1 /捆绑/ 1 / selectedBundle
/ Content / blockDiagram / 0 / bundle

并将其转换为
/ Content / blockDiagram [1] / bundle [1] / selectedBundle
/ Content / blockDiagram [2] / bundle [2] / selectedBundle
/ Content / blockDiagram [1] /套装

基本上是在路径中获取数字并将其递增1,然后更改字符串的结构。

我的尝试

function setReplicantPartListOptions(list) {
  list = "/" + list;
  var index = list.lastIndexOf("/");
  var tempString = list.substring(0, index);
  var index2 = tempString.lastIndexOf("/");
  var initialString = list.substring(0, index2);
  var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
  var lastString = list.substring(index, list.length);
  list = initialString + "[" + middlevalue + "]" + lastString;
  return list;
}

3 个答案:

答案 0 :(得分:2)

带有捕获组和替换的简单正则表达式

var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
  var next = +num + 1; // convert string to number and add one
  return "[" + next + "]";  //return the new string
})
console.log(updated)

答案 1 :(得分:2)

String.replace(RegExp, callback(match, contents))String.replace()中的callback version

就我而言,回调函数的第一个参数是结果/匹配。它接受匹配项,并使用+运算符将其转换为数字,然后将其加1。最后,我在值周围添加[ ]并返回它!

let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log( 
    str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);

答案 2 :(得分:0)

var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
  str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)