0

I need an array to make this:

Hi {nom}, you can buy {var1}

Look like this before being sent:

Hi Manuel, you can buy chips.

I have tried to do this with an array like this:

$(document).on('click','.submitMessage', function(){

    prevContent=$('textarea').val();

    $variables = array(
        '{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'
    );

    $data = prevContent;
    $data = str_replace(array_keys($variables), array_values($variables), $data);

    $.post('../actions/newMessage.php',{ms_content:$data});

And this is the error I get on loading the page:

error

7
  • 6
    Looks like you are using PHP functions in JavaScript? (str_replace, array_keys, array_values)? Commented May 7, 2015 at 10:24
  • you're mixing php and javascript..? Commented May 7, 2015 at 10:24
  • I was trying to figure out what the arrows were, I thought it was something new that I just didn't recognise, yeah this isn't valid JavaScript. Commented May 7, 2015 at 10:25
  • You prob want a structure more like: $variables = [{name:'{nom}', value:'Manuel'}, {name:'{apl}', value:'García'}...] Commented May 7, 2015 at 10:27
  • 1
    @Liam, arrow function available in new standart and in some browsers now, if before the arrow was not a string, but a variable name - it would be valid syntax for arrow func Commented May 7, 2015 at 10:35

4 Answers 4

4

You are using PHP instead of Javascript :

You can do it as below

        prevContent='Hi {nom}, you can buy {var1}';

        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);
        });

        console.log(prevContent);
Sign up to request clarification or add additional context in comments.

3 Comments

@Liam, jquery each can work with object too
@Liam , try the code it will work out , and one more thing $.each is something similar to for in loop
Worked :) I'll tick in 3 minutes
3

Like this:

'Hi {nom}, you can buy {var1}'.replace(/(\{([^\}]+)\})/gi, function($0, $1, $2){
  return { nom: 'Manulal', var1: 'chips' }[$2] || $1;
});

a bit explain regex101.com

/(\{([^\}]+)\})/gi

  • 1st Capturing group (\{([^\}]+)\})
    \{ matches the character { literally

    • 2nd Capturing group ([^\}]+)
      [^\}]+ match a single character not present in the list below
      Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
      \} matches the character } literally

    \} matches the character } literally

g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

1 Comment

Being as you've virtually minified your code an explanation would probably be useful to the OP?
2

You are mixing jQuery and PHP, Do it like the below example:

var _str = "Hi {nom}, you can buy {var1}";
var _final = _str.replace(/\{nom\}/, 'Manuel')
                .replace(/\{var1\}/, 'chips');

// _final = Hi Manuel, you can buy chips

DEMO OR Alternative:

var _str = "Hi {nom}, you can buy {var1}";
// Add as many value as you want to search and replace
var _replace = {'{nom}':'Manuel', '{var1}':'chips'};
var _final = '';
for( var i in _replace ) {
    var _regx = new RegExp(i, 'g');
    _final = _str.replace(_regx, _replace[i]);
}

alert(_final);

Comments

0

What you need to achieve could also be done using this alternative and more generic way:

// input string
var inputString = "Hi {nom}, you can buy {var1}" // or $('textarea').val();

// prepare mapping object
var mappingDetails = {
    '{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'
}

// get the regex
var generatedRegex = new RegExp(Object.keys(mappingDetails).join("|"),"gi");

// replace the placeholders
inputString = inputString.replace(generatedRegex , function(matchedText){
  return mappingDetails [matchedText];
});

// output
console.log(inputString);

Comments

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.