如何从特定字符串中删除子字符串

时间:2021-05-05 11:45:14

标签: javascript

我有一个像下面这样的字符串:

The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here].

我想打印这个完整的文本,除了 Restriction number 16. 我想跳过它,这样结果限制看起来像这样:

The combination is excluded by the following restriction\n --No-name--If-Then---- [Check the description here].

我尝试过使用各种方法,例如使用替换和拆分,但对我来说没有任何效果。

这里的复杂性是文本 Restriction number 总是固定的,但它旁边的数值,即 16 每次都可以改变。它可以是任何东西。

所以每次我们必须用空格字符替换完整的文本Restriction number followed by a number

3 个答案:

答案 0 :(得分:0)

好了。在正确位置切割原始字符串以找到动态数字。然后从原始字符串中替换该值。像这样:

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, "")

答案 1 :(得分:0)

想法是用空字符串(“”)替换子字符串。 可以使用.replace()方法完成,语法如下:

string.replace(substring, "");

或者只是,

string.replace(substring);

因为如果你在第二个参数中没有传递任何东西,它会自动将其视为一个空字符串。

let str = "The combination is excluded by the following restriction\nRestriction number 16. --No-name--If-Then---- [Check the description here].";

console.log(str.replace("Restriction number 16.", ""));

答案 2 :(得分:-1)

这个效果很好

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","")
相关问题