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

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


当前回答

const newString = string.split("data-").pop();
console.log(newString); /// 123

其他回答

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

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

Ex:-

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

希望这对你有用。

如果要替换循环中的字符串,请确保在每次迭代中初始化一个新的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___');
})

可以使用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

替换字符串的所有实例的另一种方法是使用新的(截至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; }