Neophile
Neophile

Reputation: 5880

Matching regex condition

I have a string and I would like to replace ##@@##@@ in that string to a carriage return line feed using regex.

I have been trying but haven't had much luck. My expression displays the complete text.

Expression: /^.*(##@@##@@).*$/g

String: This is my name ##@@##@@ ##@@##@@ and identity

Code: str = str.replace(/^.(##@@##@@).$/g, '\r\n');

How can I achieve what I am trying to do?

Upvotes: 1

Views: 57

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

You're working too hard. :-) Lose the ^.* and the .*$:

var str = "This is my name ##@@##@@ ##@@##@@ and identity";
str = str.replace(/##@@##@@/g, '\r\n');
console.log(str);

str.replace(/##@@##@@/g, '\r\n') says "replace the string ##@@##@@ globally in str with \r\n". In that example you end up with two replacements (with a space between) because it occurs two times.

If you want to ignore spaces between occurrences and replace thing slike ##@@##@@ ##@@##@@ with just one \r\n, then we need to adjust it slightly:

var str = "This is my name ##@@##@@ ##@@##@@ and identity";
str = str.replace(/(?:##@@##@@\s*)+/g, '\r\n');
console.log(str);

.replace(/(?:##@@##@@\s*)+/, '\r\n') says: "Replace one or more occurrences of ##@@##@@ followed by optional whitespace (\s = whitespace, * = optional) with \r\n." The (?:...) groups it together so the + ("one or more of the last thing") can be applied to the whole thing. It's a non-capturing group.

Upvotes: 2

Related Questions