![](/img/trans.png)
[英]Remove characters from string and return new string with removed characters
[英]remove text from string and return the removed part
有什么方法可以從字符串中刪除文本並返回刪除的部分,例如
var foo = "Hello world!";
var bar = foo.remove("world!");
console.log(foo); // "Hello "
console.log(bar); // "world!"
我能想到的只有
var foo = "Hello world!";
var bar;
foo = foo.replace("world!",function(m){
bar = m;
return "";
});
但我希望有更好的方法來實現它
您可以使用String.prototype.match
。
var foo = "Hello World!";
foo = foo.match("World!")[0];
您已經有了bar
的值,因此無需計算它。
var foo = "Hello world!";
var bar = "world!";
foo = foo.replace(bar,"");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.