1

I have this code:

$(document).on('click','.submitMessage,.submitStdMessage', function(e){
    prevContent=$('textarea').val();
    alert(prevContent);
    variables = {
            '{nom}' : 'Manuel',
            '{apl}' : 'García',
            '{var1}' : 'chips',
            '{var2}' : 'deportes y aventura',
            '{var3}' : 'informática y tecnología',
            '{cst1}' : 'Serrano, 28',
            '{cst2}' : 'Plaza del carmen, 32',
            '{cst3}' : 'García Luna, 15'
        };

        $.each(variables, function (key, value) {
             newContent = prevContent.replace(key, value);
        });
        alert(newContent);
    });

When a string like this is passed:

{nom}{var2}{cst2}{cst1}{cst3}

First alert says:

{nom}{var2}{cst2}{cst1}{cst3}

Second alert says:

{nom}{var2}{cst2}{cst1}García Luna, 15

If I change the order of elements inside the variables array, it always replaces the variable set on the last position of array. I need it to replace all variables send.

2 Answers 2

2

replace generally works with RegEx(you can check more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) so if you pass string as a parameter it will replace just one match.

You can use "mystring".split("wordToReplace").join("whatToReplaceWith");

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good point - those search patterns are going to be interpreted as regular expressions. In this case, the OP patterns will all work fine, but if one contained something like a . or a * there would be unexpected results.
1

Well prevContent never changes. You need to update it instead of another variable:

// Always declare local variables with var!!! 
var prevContent=$('textarea').val();
alert(prevContent);
var variables = {
        '{nom}' : 'Manuel',
        '{apl}' : 'García',
        '{var1}' : 'chips',
        '{var2}' : 'deportes y aventura',
        '{var3}' : 'informática y tecnología',
        '{cst1}' : 'Serrano, 28',
        '{cst2}' : 'Plaza del carmen, 32',
        '{cst3}' : 'García Luna, 15'
    };

    $.each(variables, function (key, value) {
         prevContent = prevContent.replace(key, value);
    });
    alert(prevContent);

1 Comment

Solved. I'll tick in 7 minutes. Very grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.