-1

I need to replace part of a string, but I don't know every character that needs to be replaced. For example, I have a string like this:

'<text align="left" fontSize="123" color="#000000">'

I need to replace whatever value is between the quotes after fontSize. This value could be "123", "12", "0", "xyz", or anything really.

I know it is something like this, but I don't fully understand:

var string = '<text align="left" fontSize="999" color="#000000">',
  newSize = 18;
string = string.replace(/fontSize="(.*)"/g, 'fontSize="' + newSize + '"');

Any help would be much appreciated. Thanks.

  • 2
    You want an explanation of the current or a solution to your problem? – Thomas Ayoub Aug 26 '15 at 14:35
  • A solution to the problem, preferably. An explanation of the current would also be helpful. It seems like my current approach is replacing everything between fontSize and the " after #000000. – Maxwell Martin Aug 26 '15 at 14:40
  • https://regex101.com/r/bM6oN1/1 this is probably what you want, your first regex will match all to the end of line... – sinisake Aug 26 '15 at 14:40
  • How about `document.getElementsByTagName("text")[0].setAttribute("fontsize",newsize)` – mplungjan Aug 26 '15 at 14:40
  • http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – epascarello Aug 26 '15 at 14:42

2 Answers2

3

Your expression is greedy, that is it will consume as many characters as it can to satisfy the expression, what you want is a non greedy expression which will stop at the first occurrence of "

/fontSize="(.*?)"/g
Musa
  • 96,336
  • 17
  • 118
  • 137
-1

this expression will also work

string = string.replace(/fontSize=.* /, ' fontSize="' + newSize + '"');
QuakeCore
  • 1,886
  • 2
  • 15
  • 33