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
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
height: 20px; whatever: 0px
, it will greedily match 20px; whatever: 0px
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.
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, ie height: 20px;
instead of the longest, height: 20px; whatever: 0px;
height: 20px; whatever: 0px;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.