簡體   English   中英

從字符串中刪除文本並返回刪除的部分

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM