rfcoder89
rfcoder89

Reputation: 185

Replace part of a string using a regexp

I have a string

string = "width: 10px; height: 20px; whatever: 0px;";

I wish to change the height part to 50px and leave the rest in tact so that the end result looks like

string = "width: 10px; height: 50px; whatever: 0px;";

I have tried string.replace("height: .*px;", "height: 50px;"); however this doesn't appear to work.

Can someone help me please

Upvotes: 0

Views: 104

Answers (3)

gotofritz
gotofritz

Reputation: 3381

You need to change the regexp to make it non-greedy

"width: 10px; height: 20px; whatever: 0px;".replace(/height: .*?px;/, "height: 50px;")

Note the question mark after star - that tells the regexp engine to find the shortest possible match, i.e. height: 20px; instead of the longest, height: 20px; whatever: 0px;

Upvotes: 2

Ethan Brown
Ethan Brown

Reputation: 27292

Guilherme's answer is partially correct: you do need to pass in a regular expression. There's another problem with your regex, though: your repetition (.* right before px) is greedy: it will match everything it can. So if you have height: 20px; whatever: 0px, it will greedily match 20px; whatever: 0px (see how it consumed everything up to the last px?). You will have to change it to a lazy match by appending the repetition with a ?:

string.replace( /height: .*?px;/, "height: 50px;" ); 

To make it more robust still, you might want to account for a variable amount of whitespace, or if the height occurs at the end of the string (which I use a lookahead for):

string.replace( /height:\s*\d+px(?=;|$)/, 'height: 50px' );

Note I also used a digit specifier (\d) instead of the wildcard metacharacter (.). Obviously this will only work if height will always be specified in integer units.

Upvotes: 2

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

If you pass a string as the first argument of your replace method, it will try to replace your string literally. To use regular expressions, you must wrap it with the / character:

yourString = yourString.replace(/height: .*?px;/, "height: 50px;");

I agree with @JamesMontagne that maybe there is a better solution for what you are trying to do. It seems a bit hacky.

Upvotes: 0

Related Questions