Javascript regex with variable - javascript

I have the following string in a variable named js:
some code here
/* start-rotateControlOptions */
some more code here
on multiple
lines
/* end-rotateControlOptions */
some code here
And I want to end up with:
some code here
some code here
Basically escape everything between these 2 specific comments.
The following works:
js = js.replace(/\/\* start-rotateControlOptions \*\/([\s\S]*)\/\* end-rotateControlOptions \*\//, '');
But now I need to have the rotateControlOptions as a variable.
This is what I have tried to no avail:
js = escapeCode(js, 'rotateControlOptions');
function escapeCode(js, identifier) {
var re = new RegExp("/\/\* start-" + identifier + " \*\/([\s\S]*)\/\* end-" + identifier + " \*\//");
js = js.replace(re, '');
return js;
}
What am I doing wrong? I get no error.

Escape all the backslahes one more time and you don't need to add the forward slash delimiter inside the RegExp constructor.
var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/");
Example:
> var str = 'some code here\n/* start-rotateControlOptions */\nsome more code here\non multiple\nlines\n/* end-rotateControlOptions */\nsome code here';
> var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/\\n");
undefined
> console.log(str.replace(re, ''))
some code here
some code here

Related

How to correctly evaluate Javascript string containing JSON.parse expression with special characters?

I need to evaluate a JS expression created in the following way
function createExprs(obj){
var decl = "var i = ";
var value = JSON.stringify(obj);
var exprs = decl + "JSON.parse('" + value + "')";
return exprs;
}
var i = createExprs({1:2});//i = "var i = JSON.parse('{"1":4}')"
eval(i); // works fine
However it fails when the obj contains any special characters
var i = createExprs("today\\.article") \\i="var i = JSON.parse('"today\\.article"')"
eval(i) // Unexpected token . in JSON
You need to escape the ":
"var i = JSON.parse('\"today.article\"')"

Invalid or unexpected token referencing HTML in JS

Code:
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = “<div><b>Announcements</b></div><table>”; <---syntax error here?
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = “</table>”; <---syntax error here?
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return “<tr><td><p><b>” + _announcementTitle + “</b></p>” + _announcementDesc +”<a href=’/Lists/Company%20Announcements/DispForm.aspx?ID=’+ _announcementID +’> Read More…</a></td></tr>”; <---syntax error here?
}
When this code is called the Chrome console says there's a invalid or unexpected token syntax error.
The error displays on lines with the double quotes and in the Chrome console the double quotes are actually replaced with icons that look like diamonds with question marks in them.
So far I've tried swapping them with single quotes and encasing the double quotes in single quotes, neither has worked.
Thank you.
Lal made a good point. I've fixed it below.
Here:
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = "<div><b>Announcements</b></div><table>";
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = "</table>";
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return "<tr><td><p><b>" + _announcementTitle + "</b></p>" + _announcementDesc +"<a href='/Lists/Company%20Announcements/DispForm.aspx?ID=" _announcementID +"'> Read More…</a></td></tr>";
This was the problem:
”<a href=’/Lists/Company%20Announcements/DispForm.aspx?ID=’+ _announcementID +’>
You had tried to close the string with the single quote, you needed a double to close it before you concatenated _announcementID
Replace “ with "
As the error message shown in the console, there is clearly an error in the “ that you are using. The “ that you are using is not the same as " that is to be used.
Thus, replace all the occurences of “ with ".
“ is LEFT DOUBLE QUOTATION MARK and " is QUOTATION MARK . You should understand that
both are different.
Check this for “ and see this for ".
You need to replace all the single quotes and double quotes with the proper characters then quote the other fragment of the link properly with the double quotes: _announcementID+"'> Read More...</a>
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = "<div><b>Announcements</b></div><table>";
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = "</table>";
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return "<tr><td><p><b>" + _announcementTitle + "</b></p>" + _announcementDesc +"<a href='/Lists/Company%20Announcements/DispForm.aspx?ID="+ _announcementID+"'> Read More...</a></td></tr>";
}

Regex mapping in Firefox context menu contentScript

I am developing context menu add-on for Firefox. I am trying to get the selectedText and validate if it is a number. If it is a number i am using that number value to process further.
But, i got stuck at a point where i am trying to replace [(,)] using regex in javascript replace method.
Following is the code which fails to map any number starting/ending with ( or ):
var menuItemLRG = contextMenu.Item({
label: "LRG",
data: "http://myurl/&val=:",
contentScript: 'self.on("click", function (node, data) {' +
' var selectedText = window.getSelection().toString();' +
' var formattedText1 = selectedText.trim();' +
' var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");' +
' var formattedText3 = formattedText2.replace(/[,\[\]()]*$/g,"");' +
' console.log(formattedText3); '+
' var regExp = new RegExp(/^[0-9]+$/);' +
' if (regExp.test(formattedText3) == true) {' +
' console.log("URL to follow :"+data+formattedText3);' +
' window.open(data+formattedText3);' +
' } '+
'});'
});
Above code fails to replace ( or ) in sample inputs: (5663812, 11620033).
But, a vanilla test like the following succeeds:
<script>
var str = "(2342423,])";
var tmpVal1 = str.replace(/^[,\[\]()]*/g,"");
var tmpVal2 = tmpVal1.replace(/[,\[\]()]*$/g,"");
var regExp = new RegExp(/^[0-9]+$/);
if (regExp.test(tmpVal2) == true) {
alert(tmpVal2);
}
</script>
After many trial and error found the issue. When we try to escape a character inside a single quotes we need to add one more escape for the escape character to get recognized, otherwise the single escape \] will be considered as ] which leads to abrupt ending of of the regex pattern.
In this case:
' var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");'
is decoded as :
var formattedText2 = formattedText1.replace(/^[,[]()]*/g,"");
instead of as:
var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");
So, by adding one more escape character for an escape character resolved the pattern correctly:
' var formattedText2 = formattedText1.replace(/^[,\\[\\]()]*/g,"");'
Sorry for wasting your time in analyzing the cause, if any.

Using variables in Javascript.replace

I am trying to inject the replace method for javascript in webview for android.
This code works:
{
mWebView.loadUrl("javascript:(function(){" +
"document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');" +
"})()");
}
Instead of putting the string in the method, however, I want to use variables. I tried using regex but it does not seem to work.
{
String old = "hello";
String new = "hi";
mWebView.loadUrl("javascript:(function(){" +
"var ol = new RegExp(old,'g');" +
"document.body.innerHTML = document.body.innerHTML.replace(ol, new);" +
"})()");
}
Is there something off with my code?
You have to quote out the variables when passing them into a string like that
{
String old = "hello";
String _new = "hi";
mWebView.loadUrl("javascript:(function(){" +
"var ol = new RegExp("+old+",'g');" +
"document.body.innerHTML = " +
"document.body.innerHTML.replace(ol, " +_new+ ");" +
"})()"
);
}
Note that new is a reserved keyword, and shouldn't be used as a variable name

Regex to match markdown image pattern with the given filename

I want to replace a markdown image pattern with the given filename in the textarea with an empty string.
So the pattern is ![alt](http://somehost/uploads/filename.jpg)
This is the code I have now:
var content = target.val();
var fileName = someDynamicValue;
var regex = new RegExp(RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
var found = regex.exec(content);
var newContent = content.replace(regex, "");
target.val(newContent);
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
For example var fileName = filename.jpg. Then I need to match ![alt](http://somehost/uploads/filename.jpg) and replace it with an empty string.
Everything works great if the content includes one image. But if there are more then one, for example:
Some text ![alt](http://somehost/uploads/filename.jpg) some text ![alt2](http://somehost/uploads/filename2.jpg) more text.
then var found includes ![alt](http://somehost/uploads/filename.jpg)![alt2](http://somehost/uploads/filename2.jpg), but I need to match only ![alt](http://somehost/uploads/filename.jpg).
What regex I need in this case?
Use non-greedy quantifiers will do:
!\[(.*?)\]\((.*?)\)
You can check it out online: https://regex101.com/r/kfi8qI
Not sure how you are trying to put the strings together but
'.*' is greedily matching up to the last filename.
So, it should probably be '.*?'.
However, if the filenames are different then it shouldn't have matched.
Another thing is you should in general stop it from running past the next [alt] with
something like '[^\[\]]*'
Edit:
RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
is the culprit.
Try
RegExp.escape('![') + '[^\]]*' + RegExp.escape(']') + RegExp.escape('(') + '[^\[\]]*?' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');

Categories