1

Is there is any way to remove a text from string and return the removed part, for example

var foo = "Hello world!";
var bar = foo.remove("world!");

console.log(foo); // "Hello "
console.log(bar); // "world!"

All I can think of is

var foo = "Hello world!";
var bar;
foo = foo.replace("world!",function(m){
  bar = m;
  return "";
});

But I hope there is a better way to achieve it

Bouh
  • 1,303
  • 2
  • 10
  • 24

2 Answers2

1

You can use String.prototype.match.

var foo = "Hello World!";
foo = foo.match("World!")[0];
undefined
  • 978
  • 1
  • 12
  • 30
1

You already have the value of bar, so there is no need to compute it.

var foo = "Hello world!";
var bar = "world!";
foo = foo.replace(bar,"");
  • 1
    you are right; my bad I should have used Regex instead of string in the example, I just wanted to make a simple example – Bouh Jan 05 '21 at 15:50
  • ill accept this since it answers the question – Bouh Jan 05 '21 at 15:54
  • Did you mean if the `bar` was a regex ? in that case you can use `foo=foo.replace(new RegExp(bar,"g"),"");` – Mario Figueiredo Jan 05 '21 at 15:57
  • Although that could replace various words, and the `bar` would turn into an array. – Mario Figueiredo Jan 05 '21 at 16:02
  • 1
    [Here is](https://gist.github.com/mostapha/fe84eeee9519257ca1b1521ec393d95c) what I'm trying to do , Thanks anyway – Bouh Jan 05 '21 at 16:22
  • For that problem i believe you are using the best possible option. However if it were me i would change the arquitecture from `string`s as code to `Map`s. And refrain from using eval unless there were really obvious necessities. [Some reasons why im commenting this here](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) – Mario Figueiredo Jan 05 '21 at 22:44
  • They also have foo, so it cna be optimized even more, if that was really the goal... – Remember Monica Aug 02 '22 at 10:49