I have an HTML element like this
<div id='test' onclick='window.location="http://example.com/";'></div>
I'm annoyed because I would like to put this into a string but I'm not able since this element use both ' and " in its syntax.
How can I store such syntax into a string?
Try This:
var data = "<div id='test' onclick='window.location=\"http://example.com/\";'></div>"
alert(data)
Just escape the strings with a \.
var myString = "<div id='test' onclick='window.location=\"http://example.com/\";'></div>";
escape the ' or " with a backslash
var testString = '<div id=\'test\' onclick=\'window.location=\"http://example.com/\";\'></div>';
alert(testString);
you can use backslash \ for putting special character in string
for example for storing string "(double quotes) and '(single quotes) you can write
var s="\"\'"
Related
I'm trying to filter a string from a onmousemove event (tooltip).
The filtered string needs to be showed as text.
The problem is that the string looks like:
This string needs to be filtered. \r\n There is also unicode in this string \u00EB.
What I want:
This string needs to be filtered. There is also unicode in this string: ë
The HTML looks as follows:
<img onmousemove="showInfo(event,'This string needs to be filtered. \r\n There is also unicode in this string: \u00EB.');" onmouseout="hideInfo();" />
This is what I tried:
$(document).ready(function() {
$('td > img').each(function() {
var toolTip = $(this).attr('onmousemove'),
comment = toolTip.match(/([\'])(\\?.)*?\1/),
parentCell = $(this).parent();
$("div.timelineRow").css("padding", "7px");
$("<td><b>Info:</b><span> " + comment[0] + "</span></td>").insertAfter(parentCell);
$(this).insertAfter(parentCell);
});
});
Try decoding your Unicode character using JSON.parse. (Note the wrapping in double quotes to make it valid JSON).
Then replace the new lines with <br> tags to convert them into HTML line break elements (The browser won't render \r\n).
e.g.
var htmlComment = JSON.parse('"' + comment[0] + '"').replace("\r\n", "<br>");
$("<td><b>Info:</b><span> " + htmlComment + "</span></td>").insertAfter(parentCell);
I've tried to get my head around regex, but I still can't get it.
I want to turn the following String + some variables into a regex:
"[url href=" + objectId + "]" + objectId2 + "[/url]"
I tried the following, since I read somewhere that brackets and slashes need to be escaped:
/\[url href=/ + objectId + /\]/ + objectId2 + /\[\/\url\]/g
But that isn't working.
I want to use it to replace the whole expression into HTML wherever it matches in a String.
You are correct that brackets and backslashes need to be escaped in a regular expression, but you can't create a regex by adding together regex literals like your /\[url href=/ + objectId + /\]/ attempt. To build a regex dynamically like that you have to use string concatenation and pass the result to new RegExp(). So as a starting point for your text you'd need this:
new RegExp("\\[url href=" + objectId + "\\]" + objectId2 + "\\[/url\\]")
Note all of the double-backslashes - that's because backslashes need to be escaped in string literals, so "\\[" creates a string containing a single backslash and then a bracket, which is what you want in your regex.
But if you want to extract the matched href and content for use in creating an anchor then you need capturing parentheses:
new RegExp("\\[url href=(" + objectId + ")\\](" + objectId2 + ")\\[/url\\]")
But that's still not enough for your purposes because objectId and objectId2 could (or will, given the first is a url) contain other characters that need to be escaped in a regex too, e.g., .+?(), etc. So here's a function that can escape all of the necessary characters:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
We can't just call that function on the whole thing, because you need unescaped parentheses for your capturing sub matches, so just call it on the two variables:
var urlRegex = new RegExp("\\[url href=("
+ escapeStringForRegex(objectId)
+ ")\\]("
+ escapeStringForRegex(objectId2)
+ ")\\[/url\\]");
Kind of messy, but seems to do the job as you can see here:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function createAnchors(str, objectId, objectId2) {
var urlRegex = new RegExp("\\[url href=(" + escapeStringForRegex(objectId) + ")\\](" + escapeStringForRegex(objectId2) + ")\\[/url\\]", "g");
return str.replace(urlRegex, "<a href='$1'>$2</a>");
}
document.querySelector("button").addEventListener("click", function() {
var str = document.getElementById("input").value;
var objectId = document.getElementById("objectId").value;
var objectId2 = document.getElementById("objectId2").value;
document.getElementById("output").value =
createAnchors(str, objectId, objectId2);
});
textarea { width : 100%; height: 80px; }
Input:<br><textarea id="input">This is just some text that you can edit to try things out. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks.</textarea>
ObjectId:<input id="objectId" value="http://test.com.au?param=1"><br>
ObjectId2:<input id="objectId2" value="Test URL"><br>
<button>Test</button>
<textarea id="output"></textarea>
Note that the above searches only for [url]s in your string that have the particular href and content specified in the objectId and objectId2 variables. If you just want to change all [url]s into anchors regardless of what href and text they contain then use this:
.replace(/\[url href=([^\]]+)\]([^\]]+)\[\/url\]/g, "<a href='$1'>$2</a>")
Demo:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function createAnchors(str) {
return str.replace(/\[url href=([^\]]+)\]([^\]]+)\[\/url\]/g, "<a href='$1'>$2</a>");
}
document.querySelector("button").addEventListener("click", function() {
var str = document.getElementById("input").value;
document.getElementById("output").value = createAnchors(str);
});
textarea { width : 100%; height: 80px; }
Input:<br><textarea id="input">Testing. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks. Another URL: [url href=https://something.com/test?param=1¶m2=123]Test URL 2[/url]</textarea>
<button>Test</button>
<textarea id="output"></textarea>
It's like:
var rx = new RegExp('\\[url\\shref='+objectId+'\\]'+objectId2+'\\[\\/url\\]');
new RegExp("[url href=" + objectId + "]" + objectId2 + "[\url]")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
I have this url that I have to pass as a javascript string. I know that I need to escape the characters, but no matter what I do I can't seem to get it right?
var v = "www.youbigboy.com/showthread.php?t=1847";
You are using double quotes inside a string declared with double quotes. You can:
Change the double quotes inside the string to single quotes
var v = "<a href='www.youbigboy.com/showthread.php?t=1847'>www.youbigboy.com/showthread.php?t=1847</a>";
Escape the double quotes inside the string with \
var v = "www.youbigboy.com/showthread.php?t=1847";
Change the double quotes outside the string to single quotes
var v = 'www.youbigboy.com/showthread.php?t=1847';
you can use single quotes ' to differentiate internal quotes, or you can escape your internal quotes \"
The code becomes:
var v = "<a href='www.youbigboy.com/showthread.php?t=1847'>www.youbigboy.com/showthread.php?t=1847</a>";
or
var v = "www.youbigboy.com/showthread.php?t=1847";
maybe this
var url = "www.youbigboy.com/showthread.php?t=1847"; //or other dynamic url's
var sb = "<a href='" + url + "'>big boy url</a>";
source: is the + operator less performant than StringBuffer.append()
I would like to do something like this:
s = s.replace(/(”)/g, '"'); // need to replace with double quotes
s = s.replace(/(“)/g, '"'); // need to replace with double quotes
s = s.replace(/(’)/g, "'"); // need to replace with single quotes
But for me this does not work. I tried all the ways.
You can use Unicode values in replace:
s = s.replace(/\u201C|\u201D/g, '"'); // for “ or ”
s = s.replace(/\u2019/g, "'"); // for ’
DEMO: http://jsfiddle.net/uM2fY/
So we open console, and see:
>>> 'test&rqduo;foo'.replace(/&rqduo;/g, '\"' );
test"foo
and with braces:
>>> 'test&rqduo;foo'.replace(/(&rqduo;)/g, '\"' );
test"foo
Everything work just like you thought. Please, check your input strings.
I have a string and I need to replace all the ' and etc to their proper value
I am using
var replace = str.replace(new RegExp("[']", "g"), "'");
To do so, but the problem is it seems to be replacing ' for each character (so for example, ' becomes '''''
Any help?
Use this:
var str = str.replace(/'/g, "'");
['] is a character class. It means any of the characters inside of the braces.
This is why your /[']/ regex replaces every single char of ' by the replacement string.
If you want to use new RegExp instead of a regex literal:
var str = str.replace(new RegExp(''', 'g'), "'");
This has no benefit, except if you want to generate regexps at runtime.
Take out the brackets, which makes a character class (any characters inside it match):
var replace = str.replace(new RegExp("'", "g"), "'");
or even better, use a literal:
var replace = str.replace(/'/g, "'");
Edit: See this question on how to escape HTML: How to unescape html in javascript?
Rather than using a bunch of regex replaces for this, I would do something like this and let the browser take care of the decoding for you:
function HtmlDecode(s) {
var el = document.createElement("div");
el.innerHTML = s;
return el.innerText || el.textContent;
}