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

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


当前回答

Ex:-

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

希望这对你有用。

其他回答

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

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

Ex:-

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

希望这对你有用。

我习惯了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'); 

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