我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
我得到了一个data-123字符串。
我如何删除数据-从字符串,而离开123?
当前回答
var ret =“data-123”。 游戏机。log(雷特);/ / prints: 123
文档。
对于所有被丢弃的事件使用:
var ret = "data-123".replace(/data-/g,'');
PS: replace函数返回一个新字符串并保持原始字符串不变,因此在replace()调用之后使用函数返回值。
其他回答
你可以使用"data-123".replace('data-', ");,如前面提到的,但是replace()只替换匹配文本的FIRST实例,如果你的字符串是"data-123data-"那么
"data-123data-".replace('data-','');
只替换第一个匹配的文本。您的输出将是"123data-"
DEMO
所以如果你想在字符串中替换所有匹配的文本,你必须使用一个带有g标志的正则表达式:
"data-123data-".replace(/data-/g,'');
你的输出是"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; }
我习惯了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
我做的这个小函数一直很适合我:)
String.prototype.deleteWord = function (searchTerm) {
var str = this;
var n = str.search(searchTerm);
while (str.search(searchTerm) > -1) {
n = str.search(searchTerm);
str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
}
return str;
}
// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!
我知道这不是最好的,但它一直对我有效:)
这与jQuery没有任何关系。你可以使用JavaScript的替换函数:
var str = "data-123";
str = str.replace("data-", "");
你也可以给这个函数传递一个正则表达式。在下面的例子中,它将替换除数字以外的所有内容:
str = str.replace(/[^0-9\.]+/g, "");