繁体   English   中英

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

[英]Replace last part of string, javascript

const str = ".1.2.1"

const str2 = ".1";

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

预期输出= ".1.2"

另一个例子:

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

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

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

更新资料

更新了字符串示例。 简单替换不起作用。

只需尝试使用正则表达式替换用空字符串替换\\.\\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); 

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

 const replace = (string, pattern) => string.replace(new RegExp(pattern.replace(/\\./g, '\\\\\\$&') + '$'), '') console.log(replace(".1.2.1", ".1")); console.log(replace("CABC", "C")); 

您可以使用String.prototype.slice

 const str = "1.2.1" const str2 = ".1"; const func = (str) => { return str.slice(0, str.lastIndexOf(".")); } console.log(func(str)); 

您可以使用RegExp创建动态正则RegExp $附加将取代str2str只有当它是在字符串的结尾

 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')) 

您可以使用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")); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM