我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
当前回答
替换字符串的所有实例的另一种方法是使用新的(截至2020年8月)string .prototype. replaceall()方法。
它接受字符串或RegEx作为第一个参数,然后用第二个参数(字符串或生成字符串的函数)替换所有匹配项。
就目前的支持而言,在撰写本文时,除了IE,所有主流桌面浏览器*(甚至是Opera!)都采用了这种方法。对于移动设备,iOS SafariiOS 13.7+, Android Chromev85+和Android Firefoxv79+也都支持。
*包括Edge/ Chrome v85+, Firefox v77+, Safari 13.1+和Opera v71+
用户更新到受支持的浏览器版本需要时间,但现在有了广泛的浏览器支持,时间是唯一的障碍。
引用:
中数 我可以使用-当前浏览器支持信息吗 .replaceAll()的提案回购
您可以在下面的代码片段中测试当前浏览器:
//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; try { console.log(p.replaceAll(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replaceAll('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?" console.log('Your browser is supported!'); } catch (e) { console.log('Your browser is unsupported! :('); } .as-console-wrapper: { max-height: 100% !important; }
其他回答
你可以使用"data-123".replace('data-', ");,如前面提到的,但是replace()只替换匹配文本的FIRST实例,如果你的字符串是"data-123data-"那么
"data-123data-".replace('data-','');
只替换第一个匹配的文本。您的输出将是"123data-"
DEMO
所以如果你想在字符串中替换所有匹配的文本,你必须使用一个带有g标志的正则表达式:
"data-123data-".replace(/data-/g,'');
你的输出是"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___');
})
1-如果是序列到你的字符串:
let myString = "mytest-text";
let myNewString = myString.replace("mytest-", "");
答案是文本
2-如果你想删除前3个字符:
"mytest-text".substring(3);
答案是est-text
我习惯了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
使用match()和Number()返回一个数字变量:
Number(("data-123").match(/\d+$/));
// strNum = 123
下面是上面这句话的作用……工作中间向外:
str.match(/\d+$/) -返回一个数组,该数组包含str结尾任意长度的数字的匹配。在这种情况下,它返回一个包含单个字符串项['123']的数组。 Number() -将其转换为数字类型。因为从.match()返回的数组包含单个元素Number()将返回该数字。