我得到了一个data-123字符串。

我如何删除数据-从字符串,而离开123?


当前回答

1-如果是序列到你的字符串:

let myString = "mytest-text";
let myNewString = myString.replace("mytest-", "");

答案是文本

2-如果你想删除前3个字符:

"mytest-text".substring(3);

答案是est-text

其他回答

可以使用slice(),如果您预先知道需要从原始字符串中分割出多少字符。它返回从起始点到结束点之间的字符。

string.slice(start, end);

下面是一些例子说明它是如何工作的:

var mystr = ("data-123").slice(5); // This just defines a start point so the output is "123"
var mystr = ("data-123").slice(5,7); // This defines a start and an end  so the output is "12"

Demo

这与jQuery没有任何关系。你可以使用JavaScript的替换函数:

var str = "data-123";
str = str.replace("data-", "");

你也可以给这个函数传递一个正则表达式。在下面的例子中,它将替换除数字以外的所有内容:

str = str.replace(/[^0-9\.]+/g, "");

我习惯了c#(尖锐)字符串。删除的方法。 在Javascript中,字符串没有remove函数,但是有substr函数。 可以使用substr函数一次或两次从字符串中删除字符。 您可以使用下面的函数删除字符串末尾的起始索引处的字符,就像c#方法首先重载string一样。删除(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

和/或你也可以让下面的函数删除字符在开始索引和计数,就像c#方法第二次重载字符串。删除(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

然后您可以使用这两个函数或其中一个来满足您的需要!

例子:

alert(Remove("data-123", 0, 5));

输出:123

str.split('Yes').join('No'); 

这将从原始字符串中替换该特定字符串的所有出现。

Ex:-

var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);

希望这对你有用。