0

I have the following string , s1 , as a part of a longer text (which doesn't have the following patter in it i.e. this pattern only happens once through out the text. The text also includes white spaces and new lines)

<!-- COMPONENTS_LIST_START -->
* [line-vis](line-chart)
* [trend-vis](trend-vis)
<!-- COMPONENTS_LIST_END -->

I want to replace it with the following string , s2 :

<!-- COMPONENTS_LIST_START -->
* [line-vis](line-chart)
* [trend-vis](trend-vis)
* [common-vis](common-vis)
<!-- COMPONENTS_LIST_END -->

I use the following RegEx but it doesn't match it :

str1.replace(/<!-- COMPONENTS_LIST_START -->(\s|.)*<!-- COMPONENTS_LIST_END -->/, str2)

Doesn't this : (\s|.)* mean , all characters including white space characters ?

Arian
  • 7,397
  • 21
  • 89
  • 177

2 Answers2

2

You are using a greedy regex so you will mess things. Btw, you can use [\S\s] ungreedy instead like this:

str1.replace(/<!-- COMPONENTS_LIST_START -->[\S\s]*?<!-- COMPONENTS_LIST_END -->/, str2)

The idea behind [\S\s]*? is to match everything until the first occurrence of your pattern, in your case <!-- COMPONENTS_LIST_END -->

And also as Trott pointed in his answer, assign the string a result:

str1 = str1.replace(/<!-- COMPONENTS_LIST_START -->[\S\s]*?<!-- COMPONENTS_LIST_END -->/, str2);
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • "this pattern only happens once through out the text" so making it non-greedy will only improve performance, not make it "more correct". Also [\S\s] should be written as [^] (the negation of nothing). – Shashank Apr 27 '15 at 23:04
2

Your regular expression works. The problem you are experiencing is that .replace() does not mutate the string. It returns a new string. If you want it to mutate the string, you need to assign the return value.

str1 = str1.replace(/<!-- COMPONENTS_LIST_START -->(\s|.)*<!-- COMPONENTS_LIST_END -->/, str2);
Trott
  • 66,479
  • 23
  • 173
  • 212
  • 1
    Actually, OP regex is greedy so technically isn't working, you are using mine :) – Federico Piazza Apr 27 '15 at 23:00
  • Oh shoot, I accidentally copy/pasted the regexp from your answer thinking I was copy/pasting from his question! Will edit... – Trott Apr 27 '15 at 23:01
  • No worries at all, just wanted to let you know that OP regex wasn't working – Federico Piazza Apr 27 '15 at 23:03
  • His works, but it replaces the entire string rather than just the inner part. But it appears that's what he wants/expects. Yours is better, though. Leaves the common prefix/suffix intact and all that. – Trott Apr 27 '15 at 23:10