我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
当前回答
Ex:-
var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);
希望这对你有用。
其他回答
const newString = string.split("data-").pop();
console.log(newString); /// 123
如果要替换循环中的字符串,请确保在每次迭代中初始化一个新的Regex。截至9/21/21,这仍然是一个已知的问题,Regex基本上错过了每一个其他匹配。当我第一次遇到这个问题时,我大吃一惊:
yourArray.forEach((string) => {
string.replace(new RegExp(__your_regex__), '___desired_replacement_value___');
})
如果你试着这样做,不要惊讶,如果只有其他所有的工作
let reg = new RegExp('your regex');
yourArray.forEach((string) => {
string.replace(reg, '___desired_replacement_value___');
})
这与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
可以使用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