I want to put "</script>" in a variable in JavaScript but it will be consider as end tag like below example:
<script>
content.value = aval + '<script> ma_gallery("' + varimgurl + '");</script>'+ sevom;
</script>
Does anyone know a solution ?
Use '<\/script>'.
In a string literal, an escaped slash is equivalent to a slash so it makes no difference to the JavaScript parser but it breaks up the end tag syntax so it isn't parsed as an end tag by the HTML parser.
(An alternative is to split it up into two strings and concatenate them together, but that is more typing, harder to read, and (albeit not significantly) less efficient).
Split "</script>" into two strings:
content.value = aval + '<script> ma_gallery("' + varimgurl + '");</scr' + 'ipt>' + sevom;
Related
I have a piece of code inside javascript tag like this:
<script type="text/javascript">
$.ajax({
...
success: function (result) {
result.TableName.forEach(
function (item) {
table.append("<tr>" +
"<td><label>" + item.X + "</label></td>" +
"<td><input id='X_" + item.Id + "' name='X_" + item.Id +"' type='text' value=" + item.X + "></td>"
its value item.X has a string value with dot (.). However, I want to use comma (,) instead of a dot in cshtml file.
Using comma should not affect the source of data but the user should see the data with a comma.
Thanks in advance.
It's still not clear to me what the .X does and if the string where you want to replace dot with comma is in the item var,
anyway let's say you have a var, containing a string with a dot and you want a comma instead, you have to use replace like so:
to replace a single dot with a comma:
item = item.replace('.', ',');
to replace all dots with commas:
item = item.replace(/./g, ',');
do this before the ajax starts (outside of it), then you can leave your code as it is.
item.X looks like having string value but it does not behave like a string. That's why I wanted to be sure so I use this:
item.X.toString().replace(".", ",");
It is not the best solution but it works now! I am waiting for your best solutions.
I am trying to directly write a Javascript variable assignment code on a ASP.NET web page.
Response.Write("<script>itHtml = '");
Response.Write("<div id=\"pop_ctrl\">Select</div><ul id=\"demo_ul\">");
foreach (Article a in arts)
{
Response.Write("<li class=\"demo_li\"><a onclick=\"ShowArticleCard(" + a.Id + ",\'" + a.User + "\',\'" + a.DateString + "\'); return false\"><div>" + it.User + "</div> <div>" + it.Title + "</div></a></li>");
}
Response.Write("</ul>");
Response.Write("';</script>");
Anchor tag in this markup executes a function ShowArticleCard() on click. This function accepts one int and two string parameters. When I am trying to add a C# string variable in place of string parameters, it replaces them like a JavaScript keyword. I tried using ',\' and \", but error persists. So, are there any levels of nested quotes we can use? If not how can I resolve this?
Try wrapping the actual value (parameter) in the quotes, like this,
onclick=\"ShowArticleCard(" + a.Id + ",'" +
a.User + "','" + a.DateString + "'); // Remaining code
Changed
I have removed the single quotes from the int type param, and removed the escape slash from the string types. They can be simply put as, '. Now when the code would run, it would be considered as a string. Otherwise (if the value is numeric) then ignore these quotes and enter them as they are. Only string-type data requires to be wrapped in either ' or ". In JavaScript they are same. In C#, ' and " have different meanings, you know that well.
Tip: Also, if you are writing something for client-side rendering, like in ASP.NET, you can easily write it as,
string.Format("<a href='{0}' onclick='func({1})'>My Link</a>",
hyperlink, param);
This would be rendered as you want it to be. :) The single quotes would be converted to double quotes once rendered in your browser. Or you can use # before the string, and write " inside the string without having to escape them.
I figured out a way of doing this. I don't know why it didn't came in my mind before.
I enclosed JavaScript function's string parameters with \\'. Like this:
ShowArticleCard(" + a.Id + ",\\'" + a.User + "\\',\\'" + a.DateString + "\\');
So that the resultant code will be:
ShowArticleCard(someid,\'someUser\',\'someDateString\');
I have variable var str as following:
var str = <option value="1">tea</option>;
I would like to make it as below
var quote_str = '<option value="1">tea</option>;'
Is there anyone can help me? Thanks in advance!
Edit:
I have tried the following code,however, it's not correct.
var quote_str = 'str';
I think that you want the semicolon outside the string literal:
var quote_str = '<option value="1">tea</option>';
If you mean that you want apostrophe characters inside the string also, you can use \' to put an apostrophe in a string delimited by apostrophes:
var quote_str = '\'<option value="1">tea</option>\'';
You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:
var quote_str = "'<option value=\"1\">tea</option>'";
If you already have a string, and want to add apostrophes around it, you concatenate strings:
var quote_str = "'" + str + "'";
Escape each single quote with a back-slash:
var quote_str = '\'<option value="1">tea</option>;\''
…or wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:
var quote_str = "'<option value=\"1\">tea</option>;'"
late update: now we have template literals, so the whole thing becomes a breeze:
var quote_str = `'<option value="1">tea</option>;'`
You can escape characters in Javascript with the \. If that's your issue
We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Using this method, we can use apostrophes in strings built with ".
'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".
"Then he said, \"Hello, World!\"";
In my case, i'm unable to use the notation of ${} in rendered Javascript inside Python Mako Templates as it's already using ${} for rendering variables in Mako:
# mako template somewhere
var quote_str = `'${str}'`;
So i just wrote a small function:
# app.js ( a real Javascript file )
function singlequote(text) {
return `'${text}'`;
}
And then I use:
# mako template somewhere
var quote_str = singlequote(str);
# So i'm able to also use something like:
let btn = '<button type="button" onclick="update(' + singlequote(myid) + "," + singlequote(mystate) + ')"> Update </button>';
I'd like to use Javascript to replace all instances of \u009 in a string
This doesn't seem to be working: .replace(/\u0009/g,'');
Do I need to escape something?
First, the question says "replace all instances of \u009 in a string".
But, the regex has replace(/\u0009/g,''); Is this a typo (different number of zeroes)?
Anyway, if the string only contains, unicode, horizontal tab characters (just one char), then the regex is fine.
If it actually contains 6 ascii chars, then the regex needs to be escaped, like so:
var oneChar = 'Pre \u0009 post';
var sixChars = 'Pre \\u0009 post';
//-- NOTE: If not using Firebug, replace 'console.log()' with 'alert()'.
console.log (oneChar + ' becomes --> ' + oneChar.replace (/\u0009/g, "") );
console.log (sixChars + ' becomes --> ' + sixChars.replace (/\\u0009/g, "") );
You need another escape .replace(/\\u009/g,''); :)
I need a regular expression to strip out any BBCode in a string. I've got the following (and an array with tags):
new RegExp('\\[' + tags[index] + '](.*?)\\[/' + tags[index] + ']');
It picks up [tag]this[/tag] just fine, but fails when using [url=http://google.com]this[/url].
What do I need to change? Thanks a lot.
I came across this thread and found it helpful to get me on the right track, but here's an ultimate one I spent two hours building (it's my first RegEx!) for JavaScript and tested to work very well for crazy nests and even incorrectly nested strings, it just works!:
string = string.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
If string = "[b][color=blue][url=www.google.com]Google[/url][/color][/b]" then the new string will be "Google". Amazing.
Hope someone finds that useful, this was a top match for 'JavaScript RegEx strip BBCode' in Google ;)
You have to allow any character other than ']' after a tag until you find ' ]'.
new RegExp('\\[' + tags[index] + '[^]]*](.*?)\\[/' + tags[index] + ']');
You could simplify this to the following expression.
\[[^]]*]([^[]*)\[\\[^]]*]
The problem with that is, that it will match [WrongTag]stuff[\WrongTag], too. Matching nested tags requires using the expression multiple times.
You can check for balanced tags using a backreference:
new RegExp('\\[(' + tags.Join('|') + ')[^]]*](.*?)\\[/\\1]');
The real problem is that you cant't match arbitrary nested tags in a regular expression (that's the limit of a regular language). Some languages do allow for recursive regular expressions, but those are extensions (that technically make them non-regular, but doesn't change the name that most people use for the objects).
If you don't care about balanced tags, you can just strip out any tag you find:
new RegExp('\\[/?(?:' + tags.Join('|') + ')[^]]*]');
To strip out any BBCode, use something like:
string alltags = tags.Join("|");
RegExp stripbb = new RegExp('\\[/?(' + alltags + ')[^]]*\\]');
Replace globally with the empty string. No extra loop necessary.
I had a similar problem - in PHP not Javascript - I had to strip out BBCode [quote] tags and also the quotes within the tags. Added problem in that there is often arbitrary additional stuff inside the [quote] tag, e.g. [quote:7e3af94210="username"]
This worked for me:
$post = preg_replace('/[\r\n]+/', "\n", $post);
$post = preg_replace('/\[\s*quote.*\][^[]*\[\s*\/quote.*\]/im', '', $post);
$post = trim($post);
lines 1 and 3 are just to tidy up any extra newlines, and any that are left over as a result of the regex.
I think
new RegExp('\\[' + tags[index] + '(=[^\\]]+)?](.*?)\\[/' + tags[index] + ']');
should do it. Instead of group 1 you have to pick group 2 then.
Remember that many (most?) regex flavours by default do not let the DOT meta character match line terminators. Causing a tag like
"[foo]dsdfs
fdsfsd[/foo]"
to fail. Either enable DOTALL by adding "(?s)" to your regex, or replace the DOT meta char in your regex by the character class [\S\s].
this worked for me, for every tag name. it also supports strings like '[url="blablabla"][/url]'
str = str.replace(/\[([a-z]+)(\=[\w\d\.\,\\\/\"\'\#\,\-]*)*( *[a-z0-9]+\=.+)*\](.*?)\[\/\1\]/gi, "$4")