Question: I'm working on an extension that essentially translates a websites UI through text replacements. I used [this article](http://readwrite.com/2014/08/29/chrome-extension-build-your-own-caaaaarbs/) as a base, but I ran into a small problem: 

For the sake of simplicity, let's say that I want to translate "books" as "presents." So using the template from the article, I write:

```
v = v.replace("books", "presents");

```

But there's another string that I'm trying to translate: "Choose books" to "Select presents." So I write the following:

```
v = v.replace("books", "presents");
v = v.replace("Choose books", "Select presents");

```

What happens is that the string "Choose books" gets replaced with "Choose presents" instead of the entire string being replaced with the intended "Select presents." 

What am I missing here? I know string commands take order into account, but is there anyway to ignore this? Could regex flags have something to do with it?

Answer: 
> 
> I know string commands take order into account, but is there anyway to ignore this?
> 
> 
> 

No. Every `replace` call ("string command") is separate and creates a new string, then the next method is called on that new string. You cannot ignore this.

> 
> Could regex flags have something to do with it?
> 
> 
> 

No. Flags only can influence the behaviour of a single replacement, they don't know anything about the other calls.

---

So what can you do against this? The obvious choice is to adapt the order of calls so that no pattern matches any previous replacement:

```
v = v.replace("Choose books", "Select presents").replace("books", "presents");

```

An alternative, which is probably what you meant with "regex flags", is to do all replacements at once. You can use a [replacement callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) to select the correct new expression:

```
v = v.replace(/(Choose )?books/g, function(match, capture) {
    if (capture) // or `match == "Choose books" or …
        return "Select presents";
    else
        return "presents";
});

```
You should replace first the more specific Strings first (or the longest), e.g.

* "Choose books with topic" => "Select presents with category"
* "Choose books" => "S
* "Select presents" "Choose" => "Select"

But the smaller the string is you do automatically replaces, the more error phrone the process will be replacing strings you didn`t want to replace. And think about case-sensitivity, e.g. "Choose books" and "choose books"

Be careful with very small words, like replace "one" with "two", then "error-phrone" will become "error-phtwo"