node.jsreplacerewriting

NODE and rewriting - Replace world alternatively in a text?


Good morning,

I would like to rewrite a text and replace words that are often repeated.

For the moment i use

srt = srt.replace(/women/gi, 'girl');

thanks


Solution

  • This code should achieve what you are trying to accomplish.

    My apologies. I thought this was Python by glancing at the code. Here is a Javascript version of the previous Python code.

    For more info on using "indexOf" vs "includes" check out this article

    JavaScript

    const word_to_replace = "amazing";
    const list_of_words = ["randWord1", "randWord2", "randWord3", "randWord4", "randWord5", "randWord6"];
    let blob = "This is an amazing text blob where the word amazing is replaced by a random word from list_of_words. Isn't that amazing!";
    let random_word;
    let randint;
    
    while (blob.indexOf(word_to_replace) !== -1) {
        randint = Math.floor(Math.random() * list_of_words.length);
        random_word = list_of_words[randint];
        blob = blob.replace(word_to_replace, random_word);
    }
    

    Python

    from random import randint
    
    
    word_to_replace = "amazing"
    
    list_of_words = ["randWord1", "randWord2",
                     "randWord3", "randWord4", "randWord5", "randWord6"]
    
    
    blob = "This is an amazing text blob where the word amazing is replaced by a random word from list_of_words. Isn't that amazing!"
    
    # Check if the word_to_replace is in the given blob.
    # If there is an occurrence then loop again
    # Keep looping until there aren't any more occurrences
    while word_to_replace in blob:
        # Get a random word from the list called list_of_words
        random_word = list_of_words[randint(0, len(list_of_words)-1)]
        # Replace only one occurrence of word_to_replace (amazing).
        blob = blob.replace(word_to_replace, random_word, 1)
    
    # Print the result
    print(blob)
    

    To do X amount of occurrences at a time change blob.replace(word_to_replace, random_word, 1) to blob.replace(word_to_replace, random_word, 3). Note the number at the end. It means "how many occurrences at a time would you like to replace?"