替换字符串的最后一部分,javascript

时间:2019-05-02 09:44:25

标签: javascript string ecmascript-6

const str = ".1.2.1"

const str2 = ".1";

const func = (str, str2) => {
 ...
}

预期输出= ".1.2"

另一个例子:

str = "CABC"
str2 = "C"
Expected output "CAB"

因此,应删除与字符串结尾匹配的字符串的最后一部分。

可以使用javascript中一些简洁的内置函数来完成此操作吗?

  

更新

更新的字符串示例。简单替换无效。

5 个答案:

答案 0 :(得分:5)

只需使用正则表达式替换用空字符串替换\.\d+$

var input = "1.2.1";
input = input.replace(/\.\d+$/, "");
console.log(input);

编辑:

假设要删除的输入的最后部分实际上包含在字符串变量中,那么我们可能被迫使用RegExp并手动构建模式:

var str = "CABC"
var str2 = "C"
var re = new RegExp(str2 + "$");
str = str.replace(re, "");
console.log(str);

答案 1 :(得分:2)

您可以从字符串中创建一个正则表达式,并通过转义点保留点,并使用字符串的结束标记仅替换最后一次出现的点。

const
    replace = (string, pattern) => string.replace(new RegExp(pattern.replace(/\./g, '\\\$&') + '$'), '')

console.log(replace(".1.2.1", ".1"));
console.log(replace("CABC", "C"));

答案 2 :(得分:0)

您可以使用String.prototype.slice

const str = "1.2.1"

const str2 = ".1";

const func = (str) => {
 return str.slice(0, str.lastIndexOf("."));
}

console.log(func(str));

答案 3 :(得分:0)

您可以使用RegExp创建动态正则表达式。附加的$仅在字符串的末尾会替换str2中的str

const replaceEnd = (str, str2) => {
  const regex = new RegExp(str2 + "$");
  return str.replace(regex, '')
}

console.log(replaceEnd('.1.2.1', '.1'))
console.log(replaceEnd('CABC', 'C'))

答案 4 :(得分:0)

您可以使用lastIndexOf检查字符串的位置以查找要查找的位置,如果它在其假定位置,则只需切片即可

function removeLastPart(str, str2)
{
  result = str;
  
  let lastIndex = str.lastIndexOf(str2);
  if (lastIndex == (str.length - str2.length))
  {
    result = str.slice(0, lastIndex)
  }
  return result;
}

console.log(removeLastPart(".1.2.1", ".1"));
console.log(removeLastPart("CABC", "C"));
console.log(removeLastPart(" ispum lorem ispum ipsum", " ipsum"));

// should not be changed
console.log(removeLastPart("hello world", "hello"));
console.log(removeLastPart("rofllollmao", "lol"));

相关问题