javascript – ¿Cómo ignorar texto que esté entre comillas con replace?

Estoy tratando de reemplazar unos textos, lo había hecho con expresiones regulares

var text = `
text = text.replace(/print(/g, "console.log(");
new Function(text)();

El texto se obtiene a través de una petición a una API REST, el problema es que si uso expresiones regulares, se va a reemplazar incluso lo que esté entre comillas, cosa que no quiero

El resultado que quiero sería algo así


Pero, como la expresión regular reemplaza todo queda así


El código que tengo hasta ahorita es

function replace(str, r) {
    if (r === str) {
        return str
            .replace("print", "console.log")
            .replace("void", "document")
            .replace("(args)", "arguments")
            .replace(":", "::")
            .replace("end", "{end}")
            .replace("fn", "abc");
    } else {
        result = str;
        r.split(" ").forEach(el => {
            result = result.replace(el, "");
        return result
            .replace("print", "console.log")
            .replace("void", "document")
            .replace("(args)", "arguments")
            .replace(":", "::")
            .replace("end", "{end}")
            .replace("fn", "abc");

function compile() {
    // fetch( => r.text()).then(resp => {
    let resp = `print("print() (args) : end fn void");`
    let inString = false;
    const split = resp.split("");
    let result = resp;
    split.forEach(el => {
        if (el === '"' || el === "'" || el === "`") {
            if (inString === false) {
                inString = true;
            } else {
                inString = false;
                result = replace(result, resp);
/*}).catch(err => {


Básicamente lo que hace es hacer un split para recorrer cada letra del string, y de encontrarse " o ', se reasigna la variable inString y ejecuta la función replace que lo que hace es reemplazar los elementos que quiero por las asociaciones del caso

Por ejemplo, si tuviera el string

void print("void print()");

Quisiera obtener

document console.log("void print()")

python3 – code to remove header and replace string in python

I am trying code to remove header from multiple csv files and add | delimiter by replacing ,
here is my code but it’s getting out-

    import time, os
from datetime import datetime
def remove_header_replace_delimiter():
    src_folder = 'C:\dir\'
    src_files = os.listdir(src_folder)
    for file_name in src_files:
        with open('C:\dir\' + file_name, 'r') as inp, open('C:\dir\' + file_name, 'w') as out:
            for line in inp:
                line = line.replace(',', '|')

java – Replace words from a file with words from a dictionary based file

I don’t think you need to test everything around opening the input file, closing it, handling exceptions, etc. For the purpose of this task, I believe you want to test your logic, and trust that FileReader or FileInputStream etc just work.

I would have a class that that can read the format of the dictionary (not provided, presumably this is FileBasedDictionary), and create a test of that class that it produces the expected Map<String, String>.

Then have a class that does business logic (i.e. the word replacement) that can operate independant of the source of the data (by taking in a flexible type like a BufferedReader). You can add a test case that demonstrates how to create a valid data source, while also demonstrating the business logic – tests are as much about documentation/demonstration as they are about checking.

import java.util.Map;

public class DictionaryReplacementService {
    private Map<String, String> dictionary;
    public DictionaryReplacementService(Map<String, String> dictionary) {
        this.dictionary = dictionary;

    public void replaceWords(BufferedReader input, BufferedWriter output)
            throws IOException {
        String line;
        while ((line = input.readLine()) != null) {
            for (Map.Entry<String, String> entry : dictionary.entrySet()) {
                line = line.replaceAll(entry.getKey(), entry.getValue());
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.LinkedHashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;

class DictionaryReplacementServiceTest {

    void test() throws IOException {
        String source = "It was the best of times, it was the blurst of times.";

        Map<String, String> dictionary = new LinkedHashMap<String, String>();
        dictionary.put("blurst", "worst");

        StringWriter outString = new StringWriter();
        try (BufferedReader in = new BufferedReader(new StringReader(source));
                BufferedWriter out = new BufferedWriter(outString)) {
            new DictionaryReplacementService(dictionary).replaceWords(in, out);

        assertEquals("It was the best of times, it was the worst of times.",


In this case, the user of your class would just need to replace StringReader with FileReader if that’s what they wanted – the DictionaryReplacementService is not interested in that.

A last note is about exceptions and return values. Instead of returning true for success and false for failure, I prefer to return void for success and just throw any exceptions that mean the success case is not possible (in my case, the try is just to ensure the resources are closed – it doesn’t catch any exceptions, and throwing an exception from a JUnit test means a test failure, which is what we want).

You said you don’t want to trivialize file i/o and you want to test what happens when problems happen, but that’s not a concern of DictionaryReplacementService – it only needs to signal that something went wrong. In a full program, you would have logic in the UI layer to try and recover (let the user know there was a problem, prompt them to try again or use a different file etc). You’re not writing that UI layer now, so I wouldn’t expect to see tests about it now.

8 – Replace placeholder in custom block with preprocess hook

In addition to @sonfd answer you also need to consider caching. The easiest way would be to add a cache context:

$variables('#cache')('contexts')() = 'user';

But then the database needs to store a cached version for each user.

Better for performance would be to postpone replacing the placeholder by attaching a lazy builder to the render array:

function mytheme_preprocess_block(&$variables) {
  $variables('#attached')('placeholders')('{{user-uid}}') = (
    '#lazy_builder' => ('_mytheme_replace_uid', ()),

which then returns the markup of the user UID:

function _mytheme_replace_uid() {
  return (
    '#markup' => Drupal::currentUser()->id(),
    '#cache' => ('contexts' => ('user')),

Drupal 9

Drupal 9 requires using only trusted callbacks. So define a class implementing TrustedCallbackInterface or RenderCallbackInterface:



namespace Drupalmytheme;

use DrupalCoreRenderElementRenderCallbackInterface;

class MythemeLazyBuilders implements RenderCallbackInterface {

  public static function replaceUid() {
    return (
      '#markup' => Drupal::currentUser()->id(),
      '#cache' => ('contexts' => ('user')),


and add it to the render array:

function mytheme_preprocess_block(&$variables) {
  $variables('#attached')('placeholders')('{{user-uid}}') = (
    '#lazy_builder' => ('DrupalmythemeMythemeLazyBuilders::replaceUid', ()),

MS-Access Beginner Replace Textbox Caption With Combo Box Selection on Button Press

I’m a complete beginner, just trying out/looking into Databases as more of a hobby, and think Microsoft Access would be an easy way to start with the whole front-end forms and back-end combination.

I just have a form with a combo box (UserNameEntry) that you can select a value from a table ‘Users’ in a ‘Alias’ field and then just press a button (Command27), and another text box will have its text replaced by that string. This is more of a test/precursor before me wanting to set it to get the record matching the ‘Alias’ value selected in the combo box, then checking if another field in that same record matches a particular value.

I don’t mind if any help is in the expression, macro or VBA builder, all is good to learn.

I tried the following expression in the On Click event of the button (Command27) (and many other alternatives) but haven’t had much luck:

=(Command27).(Caption)="(Users)!(Alias)=" & "(UserNameEntry)"

Any help would be appreciated!

lg – downloaded file disappears from file manager, but chrome wont re-download (replace), or re-name (create new file)

Android 7.1 on LG phone
“stock” chrome
I download a movie,
its a really long filename,
and the file didn’t show up in downloads

so few days later I stumble upon same movie,
try to download, and chrome says file already exists

I check “downloads” in “file manager” but there is nothing there
I choose replace file option, file is not replace
I choose create new file option, and a file shows up in downloads in file manager
but as soon as I close file manager, the file is gone

so i try it again, but this time it wont rename file
it also wont replace file (pretends its downloading, then says already downloaded, but no file)

So I added a .nomedia to the directory cause I don’t want this file randomly popping up 😉

how do I reveal this file? get rid of it?
It doesn’t show up when I connect to laptop either

How to search “people and group” list items in an entire site collection for a particular user and replace that user in powershell?

There are lots of ways a person could be displayed in a list using a “people and groups” field. I have a script that will find and update a user if they are being displayed in a list as “Name(with presence)”. I do this by searching for the string in the item fields. However, if for instance the user is only being displayed as “ID”, “first name”, “last name”, or so forth, then my script can’t find them and it will not update them. I’m working in SP2016 environment.

How can I have my script actually find the user no matter how they are displayed in the list?

Thanks in advance.

8 – Replace ‘all’ for ‘All’ at any exposed filter criteria

I’m trying to replace the ‘all‘ value for ‘All‘, because I’m getting an error if I use it as ‘all‘.

Is there any way to accomplish this?

Before: price_selector=5&price()=5&play_styles=All&theme=all

After: price_selector=5&price()=5&play_styles=All&theme=All

I tried to use: processInbound but without any success because the view is embedded in a node.

In fact Drupal form has this “issue” too:
(Status parameter = ‘all‘)

printing – Microsoft Word – Replace date created field with date printed on print

I’ve been unable so far to find a solution to this. I need to find a way to replace the date created field with date printed when someone tries to print the document.

To make it more of a challenge I have the issues below.

• This has to only be a temporary change as our users have a habit of accidentally saving which would override the correct date.
• We can’t use VBA as our system has a meltdown if there is any in the document.

Any help with this would be greatly appreciated as i’ve hit a bit of a dead end.

function construction – ReplaceThen and ReplaceAt – Cross between ReplacePart, Replace, and Extract — Request for Comment

I’m doing some work involving injecting code into held expressions, and found that I was repeating myself in a couple areas related to the available Replace and ReplacePart syntaxes. Conveniently, Extract offers us an optional third parameter where we can wrap the extracted contents in an arbitrary head before evaluation. From the documentation:

extracts parts of expr, wrapping each of them with head h before evaluation. 

Unfortunately, Replace does not offer the same convenience argument, so I created a ReplaceThen function which adds this option.

Additionally, I could not find any function which performs a Replace-like operation (including arbitrary pattern rules, not just substitution of one part with a verbatim-substituted replacement part), but only on a portion of an expression specified by an arbitrary part specification (not just a level specification). So… I created a ReplaceAt function which adds this functionality.

That said, I’m a bit of a newbie, and I want to make sure that:

  1. I considered all the edge-cases, and my code is “functionally correct” in the general case
  2. Performance is reasonably-close to optimal, for code written in native WFL. For example, I considered an approach based upon using Cases and Position, but decided that the below implementation would be more efficient.
  3. Pattern guards are effective without being overly-onerous
  4. Flexibility is sufficient enough for functions intended to cover general-case use — do you have any use-cases you run into yourself that aren’t solved by my functions, but could be with reasonable modifications? Do you have any use-cases that might motivate me to create a 3rd/N’th function within this family of Replace extensions?
  5. Forget about the “…, for code written in native WFL” restriction above. Would you use these functions for general-purpose use involving large replacement operations as-written, or might these warrant being written in C? My WFL programming skills are actually significantly weaker than their C equivalents, so it makes little difference to me. My guess is that since Replace, ReplacePart, Extract, and Dispatch are all heavily-optimized already, it’s probably not worth writing everything from scratch.

This post is a request-for-comment (RFC) on these two functions in-general, with a specific emphasis on the above questions. The code is below.

First, some boilerplate: setup a HoldComplete-like wrapper, and some dispatch tables for modifying user-provided rules and level specifications:

ClearAll(ReplaceAt`HoldComplete, partSpecPatt, replaceRulePatt,
levelSpecPattern, ReplaceThen, ReplaceAt)

(* Surrogate for HoldComplete: in case rules themselves transform HoldComplete *)
SetAttributes(ReplaceAt`HoldComplete, HoldAllComplete)

(* Boilerplate pattern guards *)

partSpecPatt = _Integer | _Span | All | {partSpecElements___ /; (And @@ 
       Thread@Unevaluated@MatchQ({partSpecElements}, partSpecPatt))};

replaceRulePatt = _Rule | _RuleDelayed | {(_Rule | _RuleDelayed) ..};

levelSpecPattern = _Integer | All | Infinity |
   -Infinity | {Repeated(_Integer | Infinity | -Infinity, {1, 2})};

(* Translate arbitrary rule(s) to never modify ReplaceAt`HoldComplete *)
(* e.g. if the rule was _(x_):>Identity(x) *)

ruleExceptTransform = 
  Dispatch((h : Rule | RuleDelayed)(l_, r_) :> 
    h(Except(ReplaceAt`HoldComplete | _ReplaceAt`HoldComplete, l), r));

(* Translate level spec to account for ReplaceAt`HoldComplete *)

levelSpecTransform = 
  Dispatch({{n1_, n2_Integer?Positive} :> {n1, n2 + 1}, 
    n_Integer?Positive :> n + 1, {n_Integer?Positive} :> {n + 1}});

(* Sugar: make user calls to Options(...) return something *)

Options(ReplaceThen) = Options(Replace);
Options(ReplaceAt) = Options(Replace);

Next, here are ReplaceThen and ReplaceAt:

With({ruleExceptTransform = ruleExceptTransform, 
  levelSpecTransform = levelSpecTransform},
 ReplaceThen(expr_, rules : replaceRulePatt, 
   levelSpec : levelSpecPattern : {0}, wrap_Symbol : Identity, 
   opts : OptionsPattern()) := wrap @@ Replace(
    Replace(rules, ruleExceptTransform, {0, 1}),
    Replace(levelSpec, levelSpecTransform),
 ReplaceAt(expr_, rules : replaceRulePatt, partSpec : partSpecPatt, 
   levelSpec : levelSpecPattern : {0}, opts : OptionsPattern()) :=
     Extract(Unevaluated@expr, partSpec, ReplaceAt`HoldComplete),
     Replace(rules, ruleExceptTransform, {0, 1}),
     Replace(levelSpec, levelSpecTransform),
    ReplaceAt`HoldComplete(x_) :> RuleDelayed(partSpec, x)

We might as well support Operator forms of the above, while we’re at it:

ReplaceThen(rules : replaceRulePatt, 
   levelSpec_ : levelSpecPattern : {0}, wrap_Symbol : Identity, 
   opts : OptionsPattern()) := 
  Function(expr, ReplaceThen(expr, rules, levelSpec, wrap, opts), 
    HoldFirst) /. DownValues@ReplaceThen;

(* Remember Unevaluated if not inlining with DownValues *)

ReplaceAt(rules : replaceRulePatt, partSpec : partSpecPatt, 
   levelSpec : levelSpecPattern : {0}, opts : OptionsPattern()) := 
    ReplaceAt(expr, rules, partSpec, levelSpec, opts)) /. 

Alternatively, I could have written ReplaceAt in terms of ReplaceThen, but I think that my formal proposal for these functions would be as-written above. The below alternative relies upon the fact that RuleDelayed consumes Unevaluated from any expression which starts with Unevaluated:

ReplaceAt(expr_, rules : replaceRulePatt, partSpec : partSpecPatt, 
  levelSpec : levelSpecPattern : {0}, opts : OptionsPattern()) := 
 With({subExpr = 
    Extract(Unevaluated@expr, partSpec, 
     ReplaceThen(rules, levelSpec, Unevaluated, opts))},
  ReplacePart(expr, partSpec :> subExpr))

ReplaceAt(rules : replaceRulePatt, partSpec : partSpecPatt, 
  levelSpec : levelSpecPattern : {0}, opts : OptionsPattern()
  ) := With({replaceThenOp = 
    ReplaceThen(rules, levelSpec, Unevaluated, opts)},
   With({subExpr = Extract(Unevaluated@expr, partSpec, replaceThenOp)},
    ReplacePart(expr, partSpec :> subExpr))))

That concludes the function definitions. Now, let’s define a test expression to run through the two functions and their Operator-form versions:

ClearAll(F, G)
testExpr = Hold(
   1 + 1, F(Plus(a, b), Plus(c, d), Times(e, Plus(f, g))), 2 + 2, h + i

Then, let’s test ReplaceThen:

ReplaceThen(testExpr, F :> G, {2}, Heads -> True)
ReplaceThen(Unevaluated(3 + 3), Plus :> Times, {1}, Hold, Heads -> True)
ReplaceThen(Plus :> Times, {1}, Hold, Heads -> True)
%@Unevaluated(3 + 3)

The output is what I would expect:

Hold(1 + 1, G(a + b, c + d, e * (f + g)), 2 + 2, h + i)
Hold(3 * 3)
 Hold @@ Replace(ReplaceAt`HoldComplete(expr$), 
   Replace(Plus :> Times, Dispatch(Length : 1), {0, 1}), 
   Replace({1}, Dispatch(Length : 3)), Heads -> True), HoldFirst)
Hold(3 * 3)

Now, let’s test ReplaceAt:

ReplaceAt(testExpr, Plus :> Times, {2}, {0, Infinity}, Heads -> True)
ReplaceAt(testExpr, F :> G, {2}, {1}, Heads -> True)
ReplaceAt(testExpr, x_ :> x^2, {2}, {-1})
ReplaceAt(testExpr, x_ :> x^2, {2}, {-Infinity, Infinity})

ReplaceAt(x_ :> x^2, {2}, {-Infinity, Infinity})

Again, the results match what I would expect:

Hold(1+1,F(a * b,c * d,e * (f * g)),2+2,h+i)
Hold(1+1,G(a+b,c+d,e * (f+g)),2+2,h+i)
Hold(1+1,F(a^2+b^2,c^2+d^2,e^2 * (f^2+g^2)),2+2,h+i)
Hold(1+1,F((a^2+b^2)^2,(c^2+d^2)^2,(e^2 * (f^2+g^2)^2)^2)^2,2+2,h+i)
    Extract(Unevaluated(expr$), {2}, ReplaceAt`HoldComplete), 
    Replace(x_ :> x^2, Dispatch(Length : 1), {0, 1}), 
    Replace({-(Infinity), (Infinity)}, Dispatch(Length : 3))), 
   ReplaceAt`HoldComplete(x$_) :> {2} :> x$)))
Hold(1+1,F((a^2+b^2)^2,(c^2+d^2)^2,(e^2 * (f^2+g^2)^2)^2)^2,2+2,h+i)

That said, perhaps there are some edge-cases that I haven’t thought through, or performance/flexibility could be increased. Or perhaps you can think of an alternative way to perform the same tasks, written in WFL, which is simply more elegant.

Thanks in advance for feedback / critiques!

EDIT: I’ll start by critiquing myself — I noticed that I’m inconsistent in the Operator forms of ReplaceThen and ReplaceAtReplaceThen uses HoldFirst, while ReplaceAt does not. On the one hand, I want to be able to use the Operator forms of these functions as the 3rd argument to Extract, receive an unevaluated expression, and pass-on that expression, still Unevaluated, to downstream Replace/ReplacePart functions. On the other hand, if the user provides a variable to the Operator forms of my functions (e.g. myReplaceAtOperator(testExpr)), I want to support that too. But if I make the Operator forms include Function(..., HoldFirst) and pass-on Unevaluated(expr) to downstream functions, then Replace/ReplacePart will just receive a Symbol, not the expression it contains. Still thinking this part through… I may just make an OptionValue so that you can choose when you want the Operator to have HoldFirst and when you do not…