Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从特定字符串中删除子字符串_Javascript - Fatal编程技术网

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.”,“”)。替换(/Restriction number[0-9]+\./,“”)
@georg这可能是最好的答案谢谢@georg。这是最好的答案,完全符合我的要求。