0

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?

0

2 Answers 2

4

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");
Sign up to request clarification or add additional context in comments.

2 Comments

Your Kung-Fu is stronger than mine. +1 ... Although your style is imperfect, it can be compacted like this: .replace(/([A-Za-z]+)/g, "$('$1').value"); :P
@Cerbrus: Yes, you are right, I didn't think of that option. The callback version is useful if it needs any further expansion.
1

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.

10 Comments

Thanks, this seems to do the trick, but it goes for only the first ocurrence, how i make this for all ocurrences? \b is a word boundary so, \bword\b what does the other / characters do at the beginning and end?
The / characters are regex delimiters. They simply mean start regex and end regex. Use /\btime\b/g to make the regex work on all occurrences. (So, add a g after the second /)
nice. Also if the value time is a variable string how can i mix with the regex?this doesn't seem to be working: var test=/\+variable+\b/g
In that case you'll have to use the RegExp constructor, instead of a literal. Replace: /\btime\b/g with new RegExp("/\b"+variable+"\b/", "g")
Humm seems to be failing to find anything...strange
|

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.