tags:

views:

49

answers:

3

Hello. I have a string which contains a nonvariable part, a variable numnber and another nonvariable part. I want to user replace(), to change only the variable part into a value a user chooses. I'm a noob at javascript, and even a bigger noob in reg expressions, so sorry if this is something trivial.

Anyway, i have a string like this:

"first nonvar part: "+any_integer+"last nonvar part".

i'd like to use regexp to replace any_integer.

Can i somehow combine string and regular expression matching to match the string by it's non variably parts with an unknown number in between?

So i can use:

replace("first nonvar part: "+any_number+"last nonvar part","first nonvar part: "+user_input+"last nonvar part")

or something similar.

Many thanks

+1  A: 
var str = original.replace(/(non var)\d(non var)/​​​​​​​​​​​​​​​​​​​​​, "$1" + input + "$2");

Replace the "non vars" with your non-variables.

quantumSoup
+2  A: 

If the nonvariant parts of the string doesn't contain digits, you can just specify the digits in the expression:

str = str.replace(/\d+/, replacement);

If you want to create the regular expression by concatenating strings, you use the Regexp constructor:

var first = "first nonvar part: ";
var last = "last nonvar part";
var re = new Regexp("^" + first + "\\d+" + last + "$");
str = str.replace(re, replacement);

Note that if the nonvariant strings contain any characters that has a special meaning in a regular expression, they need to be escaped.

Guffa
In a string that should be `"\\d+"`. JavaScript usually ignores undefined escapes, so are left with `d+`.
Kobi
@Kobi: Yes, of course. I corrected the code.
Guffa
A: 

Wow, you guys are fast. Thanks

@Guffa: Thank you very very much. Your thing works like a charm

@Kobi: Yes, at first glance "nonvar1"+userinput+"nonvar2" looks like a solution, but i have a problem where i have to get to various parts of html by saving them as strings, and i have to update all of them once the change is made.

Anyway, Guffa's solution does exactly what i wanted.

pinetree