Javascript regex with deep objects replacement issue - javascript

Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");

See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?

You need to escape the '.' characters in the string you're passing in as the fieldName parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically, fieldName is being treated as part of a regex pattern.
If you don't want fieldName to be evaluated as regex code, you might want to consider using string manipulation for this instead.
Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.

Related

RegEx working in JavaScript but not in C#

I currently have a working WordWrap function in Javascript that uses RegEx. I pass the string I want wrapped and the length I want to begin wrapping the text, and the function returns a new string with newlines inserted at appropriate locations in the string as shown below:
wordWrap(string, width) {
let newString = string.replace(
new RegExp(`(?![^\\n]{1,${width}}$)([^\\n]{1,${width}})\\s`, 'g'), '$1\n'
);
return newString;
}
For consistency purposes I won't go into, I need to use an identical or similar RegEx in C#, but I am having trouble successfully replicating the function. I've been through a lot of iterations of this, but this is what I currently have:
private static string WordWrap(string str, int width)
{
Regex rgx = new Regex("(?![^\\n]{ 1,${" + width + "}}$)([^\\n]{1,${" + width + "}})\\s");
MatchCollection matches = rgx.Matches(str);
string newString = string.Empty;
if (matches.Count > 0)
{
foreach (Match match in matches)
{
newString += match.Value + "\n";
}
}
else
{
newString = "No matches found";
}
return newString;
}
This inevitably ends up finding no matches regardless of the string and length I pass. I've read that the RegEx used in JavaScript is different than the standard RegEx functionality in .NET. I looked into PCRE.NET but have had no luck with that either.
Am I heading in the right general direction with this? Can anyone help me convert the first code block in JavaScript to something moderately close in C#?
edit: For those looking for more clarity on what the working function does and what I am looking for the C# function to do: What I am looking to output is a string that has a newline (\n) inserted at the width passed to the function. One thing I forgot to mention (but really isn't related to my issue here) is that the working JavaScript version finds the end of the word so it doesn't cut up the word. So for example this string:
"This string is really really long so we want to use the word wrap function to keep it from running off the page.\n"
...would be converted to this with the width set to 20:
"This string is really \nreally long so we want \nto use the word wrap \nfunction to keep it \nfrom running off the \npage.\n"
Hope that clears it up a bit.
JavaScript and C# Regex engines are different. Also each language has it's own regex pattern executor, so Regex is language dependent. It's not the case, if it is working for one language so it will work for another.
C# supports named groups while JavaScript doesn't support them.
So you can find multiple difference between these two languages regex.
There are issues with the way you've translated the regex pattern from a JavaScript string to a C# string.
You have extra whitespace in the c# version, and you've also left in $ symbols and curly brackets { that are part of the string interpolation syntax in the JavaScript version (they are not part of the actual regex pattern).
You have:
"(?![^\\n]{ 1,${" + width + "}}$)([^\\n]{1,${" + width + "}})\\s"
when what I believe you want is:
"(?![^\\n]{1," + width + "}$)([^\\n]{1," + width + "})\\s"

how to replace all occurrence of string between two symbols?

I'm working with RegEx on Javascript and here is where I stuck.
I have a simple string like
<html><body><span style=3D"font-family:Verdana; color:#000; font-size:10pt;=
"><div><font face=3D"verdana, geneva" size=3D"2">http://72.55.146.142:8880/=
order003.png.zip,120</body></html>
all i need to do is write javascript which can replace all strings in with "<" and ">" symbol.
I wrote something like this -
var strReplaceAll = Body;
var intIndexOfMatch = strReplaceAll.indexOf( "<" );
while (intIndexOfMatch != -1){
strReplaceAll = strReplaceAll.replace(/<.*>/,'')
intIndexOfMatch = strReplaceAll.indexOf( "<" );
}
but the problem is if body contains -
test<abc>test2<adg>
it will give me -
test
only or if body contains like -
<html>test<abc>test2<adg>
it will give me nothing please let me know how i can get-
testtest2
as a final output.
Try this regex instead:
<[^>]+>
DEMO:
http://regex101.com/r/kI5cJ7/2
DISCUSSION
Put the html code in a string and apply to this string the regex.
var htmlCode = ...;
htmlCode = htmlCode.replace(/<[^>]+>/g, '');
The original regex take too much characters (* is a greedy operator).
Check this page about Repetition with Star and Plus, especially the part on "Watch Out for The Greediness!".
Most people new to regular expressions will attempt to use <.+>. They will be surprised when they test it on a string like This is a <EM>first</EM> test. You might expect the regex to match <EM> and when continuing after that match, </EM>.
But it does not. The regex will match <EM>first</EM>. Obviously not what we wanted.
/(<.*?>)/
Just use this. Replace all the occurrences with "".
See demo.

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

Escaping single quotes in JavaScript string for JavaScript evaluation

I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
// Here, the string needs to be escaped for single quotes for the eval
// to work as is. The following does NOT work! Help!
strInputString.replace(/'/g, "''");
var strTest = "strResult = '" + strInputString + "';";
eval(strTest);
alert(strResult);
}
And I want to alert it, saying: fsdsd'4565sd.
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \ and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \ was the work around.
Only this worked for me:
searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"
So, the result variable will contain "d\'av".
I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)
That worked for me.
string address=senderAddress.Replace("'", "\\'");
There are two ways to escaping the single quote in JavaScript.
1- Use double-quote or backticks to enclose the string.
Example: "fsdsd'4565sd" or `fsdsd'4565sd`.
2- Use backslash before any special character, In our case is the single quote
Example:strInputString = strInputString.replace(/ ' /g, " \\' ");
Note: use a double backslash.
Both methods work for me.
var str ="fsdsd'4565sd";
str.replace(/'/g,"'")
This worked for me. Kindly try this
The regular expression in the following code also handles the possibility of escaped single quotes in the string - it will only prepend backslashes to single quotes that are not already escaped:
strInputString = strInputString.replace(/(?<!\\)'/g, "\\'");
Demo: https://regex101.com/r/L1lF7J/1
Compatibility
The regex above uses negative lookbehind, which is widely supported but if using an older Javascript version, this clunkier regex (which uses a capturing group backreference instead) will also do the job:
strInputString = strInputString.replace(/(^|[^\\])'/g, "$1\\'");
Demo: https://regex101.com/r/9niyYw/1
strInputString = strInputString.replace(/'/g, "''");

JavaScript - Regular Expressions

I have an HTML page with a text box. This text box has an id of "myTextBox". I am trying to use a regular expression in JavaScript to replace certain values in the text box with another value. Currently, I am trying the following
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null)
{
var current = new String(tb.value);
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
}
}
Based on this code, if I had the value "2ft" in the myTextBox, I would expect the current variable to be "2'". However, it always shows an empty string. I fear there is something that I am misunderstanding in relation to regular expressions in JavaScript. What am I doing wrong?
Thank you!
Rewrite your pattern to:
(ft\.?|foot|feet)
This will match "ft" or "ft." and "foot" or "feet".
When writing code that uses regular expressions that won't behave, assume (first) that it is your regex that is the problem. Thanks to the compact and esoteric "programming" of regular expressions, it's quite easy to make a mistake you don't see.
If you test the following in Firebug to yield a correct result:
"2ft".replace(/(ft\.?|foot|feet)/ig, "'")
You will get "2'" in your console.
So this answer ought to solve your problem, if the regex is your problem in the first place. Like Rubens said, please check the ID of your textbox and ensure that the item is correctly retrieved.
As The Wicked Flea says, the literal '.' in your regex needs to be escaped. If it's in a character class it can be written un-escaped, but outside of one it must be escaped.
The following works for me:
<script>
var current = "2ft";
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
</script>
Are you sure that tb.value is evaluating properly?
I ran your code using IE8,Chrome and FF3 with no problems.
Please check if your textbox id is correct.
The problem is that you're alternating explicit groupings. Instead you can just do something like the following:
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null) {
current = tb.value.replace(/\s*(ft\.|ft|foot|feet)\b/ig, "'");
alert(current);
}
}
Also, note the \s* which will strip leading spaces and the \b which marks the beginning/end of a word. I also added feet.

Categories