Actually, I want to replace all matched string used as a key of given object to find the value using javascript regular expression. For example: we have string as
hello,how are you???!!OH!! i am fine. what about you, !!FRIEND!!? I am !!GOOD!!.
and object is like var mapper={"OH":"oh+","FRIEND":"friend+","GOOD":"good+"}
Then output should be like:
hello,how are you???OH+ i am fine. what about you, FRIEND+? I am GOOD+.
As starting and ending !! sign will be replaced with only + sign in the end.
var mapper={"OH":"oh+","FRIEND":"friend+","GOOD":"good+"};
data=data.replace(new RegExp("!![A-Z]*!!", 'g'),modifiedSubstring);
Actually, I want to replace all matched string used as a key of given object to find the value using javascript regular expression. For example: we have string as
hello,how are you???!!OH!! i am fine. what about you, !!FRIEND!!? I am !!GOOD!!.
and object is like var mapper={"OH":"oh+","FRIEND":"friend+","GOOD":"good+"}
Then output should be like:
hello,how are you???OH+ i am fine. what about you, FRIEND+? I am GOOD+.
As starting and ending !! sign will be replaced with only + sign in the end.
var mapper={"OH":"oh+","FRIEND":"friend+","GOOD":"good+"};
data=data.replace(new RegExp("!![A-Z]*!!", 'g'),modifiedSubstring);
I am new to use regular expression but tried some code as placed above. In this expression what should I write instead of modifiedSubstring
.
-
You only replaced ending
!!
with a+
. – user2705585 Commented Mar 10, 2016 at 20:14 - no, it will match uppercase words starts and end with !!. then replace all of them with + appending in last – gurvk Commented Mar 10, 2016 at 20:17
3 Answers
Reset to default 4Try using RegExp
/(\!+(?=[A-Z]+))|(\!+(?=\s|\?|\.|$))/g
to match multiple !
characters followed by capital letters , or multiple !
characters followed by space character, .
character or end of input. Replace first capture group with ""
empty string, replace second capture group with +
character
var data = "hello,how are you???!!OH!! i am fine. what about you, "
+ "!!FRIEND!!? I am !!GOOD!!.";
data = data.replace(/(\!+(?=[A-Z]+))|(\!+(?=\s|\?|\.|$))/g
, function(match, p1, p2) {
return p1 ? "" : "+"
});
document.body.innerHTML = data;
You can capture the data inside the desired pattern and return it with your desired formatting by using parentheses and $1
data = "hello,how are you???!!OH!! i am fine. what about you, !!FRIEND!!? I am !!GOOD!!.";
data=data.replace(new RegExp("!!([A-Z]*)!!", 'g'),"$1+");
You can look for instances like !!word!!
and replace it to word+
using this regex.
Regex: !!([A-Z]*?)!!
Explanation:
- It will match
!!
followed by aWORD
followed by!!
.
Replacement to do:
\1+
This will replace the match with justWORD+
asWORD
falls in first captured group.