Reputation: 7719
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 ?
Upvotes: 0
Views: 65
Reputation: 70055
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);
Upvotes: 2
Reputation: 30985
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);
Upvotes: 2