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.
Try 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+");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With