Maxrunner
Maxrunner

Reputation: 1965

Javascript - Replace substring from string where the value is between specific characters

So I have this string, that represents a math expression:

(timezone*timelapse)-time

Each word represents an id from an input field, and currently i was merely replacing each word with a prototype js expression to be evaled later:

$('timezone').value,

$('timelapse').value

The problem is the last id. By the time i reach it, my expression is currently like this:

($('timezone').value*$('timelapse').value)-time

So when I search for the word time to replace it with $('time').value it will affect the first two values and messing the final expression.

My question here is: How can I replace the correct word here?

Since this a math expression the word should probably be between any math symbols like this:

(+-/* **word** +-/*)

[empty space] **word** +-/*)

(*-/* **word** [empty space]

Or not?

Upvotes: 0

Views: 375

Answers (2)

Guffa
Guffa

Reputation: 700342

You can replace all with one replacement, then you don't have the double replacement problem:

exp = exp.replace(/([A-Za-z]+)/g, function(m){
  return "$('" + m + "').value";
});

If it's a straight replacement without any logic, you can also use the caught value in a replacement string, as Cerbrus suggested:

exp = exp.replace(/([A-Za-z]+)/g, "$('$1').value");

Upvotes: 4

Cerbrus
Cerbrus

Reputation: 72857

Try this:

var newString = oldString.replace(/\btime\b/, "$('time').value")

\b is a word boundary, meaning the regex only matches time if it's a stand-alone word, not when it's directly followed or preceded by any word characters.

Upvotes: 1

Related Questions