replace values in symbols in a string

5

I have the following string:

Var text='¡Hola $var1$! Gracias $var2$'

How can I replace what is between $ by the value of the variable. Example:

var1="Juan", var2="Pedro"

Resultado='¡Hola Juan! Gracias Pedro'

The text can have more variables and content, which is why I can not do with indexOf

Try with exp. regular, but not used very well.

var exp = text.search(/'$'[a-z A-Z]'$'/i);
    
asked by Alexis Granja 11.07.2017 в 16:47
source

2 answers

3

What we can do is convert your text into the Javascript Literal Templates system.

First we use a

answered by 11.07.2017 / 16:53
source
4

You can use this snippet, which is to replace the tokens $id$ with the property id in the object contexto

function analizar(mensaje, contexto)
{
	var tokens = /\$(\w+)\$/g
	return mensaje.replace(tokens, function(token, $1)
	{
		return contexto[$1]		
	})
}

var texto = '¡Hola $var1$! Gracias $var2$'
var contexto = {var1: 'Juan', var2: 'Pedro'}
console.log(analizar(texto, contexto)) // Forma ideal

var var1 = 'María'
var var2 = 'Ana'
console.log(analizar(texto, this)) //No recomendado
    
answered by 11.07.2017 в 17:41