Javascript 如何从特定字符串中删除子字符串
我有一个字符串,如下所示:Javascript 如何从特定字符串中删除子字符串,javascript,Javascript,我有一个字符串,如下所示: The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here]. 我想打印此完整文本,除了限制编号16。我想跳过它,因此生成的限制将如下所示: The combination is excluded by the following restriction\n --N
The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here].
我想打印此完整文本,除了限制编号16。
我想跳过它,因此生成的限制将如下所示:
The combination is excluded by the following restriction\n --No-name--If-Then---- [Check the description here].
我尝试过使用各种方法,比如使用replace和split,但没有任何方法能完全适合我
这里的复杂性是文本限制编号
始终是固定的,但其旁边的数值,即16
每次都可能发生变化。它可以是任何东西
因此,每次我们都必须将完整的文本限制号后跟一个数字
替换为空格字符。这很有效
console.log("The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here].".replace("Restriction number 16.",""))
将其用作:
"your string".replace("your replace string","")
好了,开始吧。在正确的位置切片原始字符串以查找动态编号。然后从原始字符串中替换该值。像这样:
let myString = "The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here]."
let i = myString.indexOf("Restriction number ") + "Restriction number ".length
let s2 = myString.substr(i)
let dynamicNumber = s2.substr(0, s2.indexOf(' '))
let stringToReplace = "Restriction number " + dynamicNumber
let finalString = myString.replace(stringToReplace, "")
想法是用空字符串(“”)替换子字符串。 可以使用
.replace()
方法完成,语法如下所示:
string.replace(子字符串“”)代码>
或者只是
string.replace(子字符串)代码>
因为如果在第二个参数中没有传递任何内容,它会自动将其视为空字符串。
let str=“该组合被以下限制排除\n限制编号16。--无名称--If Then--[检查此处的说明]”;
日志(str.replace(“限制编号16.”,“”)这里的问题是,限制编号后的数值不是每次都固定的。它可以改变。所以我们必须用空格代替限制数+动态数值。哦,好的。我会更新我的答案。谢谢@Viktor W。它现在可以正常工作了。你需要一个正则表达式:。替换(/Restriction number[0-9]+\./,“”)
@georg这可能是最好的答案谢谢@georg。这是最好的答案,完全符合我的要求。