我得到了一个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; }

其他回答

我做的这个小函数一直很适合我:)

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!!

我知道这不是最好的,但它一直对我有效:)

你可以使用"data-123".replace('data-', ");,如前面提到的,但是replace()只替换匹配文本的FIRST实例,如果你的字符串是"data-123data-"那么

"data-123data-".replace('data-','');

只替换第一个匹配的文本。您的输出将是"123data-"

DEMO

所以如果你想在字符串中替换所有匹配的文本,你必须使用一个带有g标志的正则表达式:

"data-123data-".replace(/data-/g,'');

你的输出是"123"

以及接下来

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