我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开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___');
})
其他回答
我习惯了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
const newString = string.split("data-").pop();
console.log(newString); /// 123
var ret =“data-123”。 游戏机。log(雷特);/ / prints: 123
文档。
对于所有被丢弃的事件使用:
var ret = "data-123".replace(/data-/g,'');
PS: replace函数返回一个新字符串并保持原始字符串不变,因此在replace()调用之后使用函数返回值。
使用match()和Number()返回一个数字变量:
Number(("data-123").match(/\d+$/));
// strNum = 123
下面是上面这句话的作用……工作中间向外:
str.match(/\d+$/) -返回一个数组,该数组包含str结尾任意长度的数字的匹配。在这种情况下,它返回一个包含单个字符串项['123']的数组。 Number() -将其转换为数字类型。因为从.match()返回的数组包含单个元素Number()将返回该数字。