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);
Related
I have a number of strings coming back from the database and I need to separate them into 2 lines based on a specific word that the backend person can insert in the string. (The word or symbol can be anything.)
I have tried the following:
var str = "some string some string space some string";
str = str.replace(/space/g, "\n")
console.log(str);
but the string still appears over one line only.
...
var str = "some string some stringspacesome string";
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
console.log(str);
var screenHeight = (this.state.windowHeight -90) + 'px';
return (
<div>
<Header />
<section className={"main " + this.state.color_name} style={{minHeight: screenHeight}}>
<div className="content-wrapper">
<div className="content" >
<h1>{str}</h1>
...
After the replacement, the str variable is going to be used as the contents of an h1 element.
If you want the string to be used as the contents of an HTML tag, then \n isn't the proper way to have it display on two lines. Rather, you'll need to use an html break tag of <br/>. You can either replace that into your strings, like this:
str = str.replace(/space/g, "<br/>")
Or for simplicity's sake, since you mentioned that the "space" string to replace can be anything, it seems like you could just skip the replacement altogether and use the desired replacement on the backend.
I have received the following string from my ajax request:
As per json doc, "quotes must be escaped "
This is stored in data.description and is embedded in the template as:
''
data-title's value is used as a caption for lightbox plugin pop up. I tried the following function:
var HtmlEncode = function(s) {
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
as:
''
Now since the data.description contains multiple quotes javascript assumes them as multiple argument and throws error. I searched many other Stackoverflow posts which suggest to append the data in a div and retrieve its inner HTML but that is possible in my case.
Thanks
Change only the quotes that are the same as those will be surrounding the data-title. Like this:
var description = data.description.replace(/"/g, "'");
var template = '';
You can replace the double quotes in your string with single quotes or any other symbol in order for it to work inside double quotes.
you can do this with String.replace(/["]+/g,"'") this will replace the double quotes in the string with a single quote, the g in the reg-ex tells it to use all the string.
you can also fake it by using 2 single quotes like this String.replace(/["]+/g,"''"), and it will fake double quotes for you.
var HtmlEncode = function(s) {
return s.replace(/["]+/g,"''");
}
Solution 1
Escape it with replace and a regexp:
var HtmlEncode = function(s) {
return s.replace(/"/g, '\\"').replace(/'/g, "\\'");
}
''
Solution 2
Let jQuery doing this for you (only if you are using it).
var tpl = $('');
tpl.data('title', data.description);
Try to replace the quotes with HTML entity equivalents after which you can then safely use it on attributes.
var desc = data.description.replace(/'/g, "'").replace(/"/g, """);
''
Here's a Fiddle to demonstrate the solution.
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
How can i go round wrapping a given string separated with commas in jquery with quotes
Say
respons_pre =response[0].s_date; //in code
response_pre= 10/01/2015, 10/02/2015, 11/20/2015;
so as to be like
response_pre2='10/01/2015', '10/02/2015', '11/20/2015';
Just use replace() to replace every occurance of , with ', ' for this & add quotes in starting & end of string.
respons_pre =response[0].s_date;
var responseString = "\'"+response_pre.replace(/, /g,'\', \'')+"\'";
Working Example:
var response_pre= "10/01/2015, 10/02/2015, 11/20/2015";
var responseString = "\'"+response_pre.replace(/, /g,'\', \'')+"\'";
document.body.innerHTML= "Response String: "+response_pre+'<br/>'+"Output String: "+responseString;
If I understood your question, you have an array of Date objects, which you would like to transform into a string containing the dates represented in the MM/dd/yyyy format, enclosed with single quotes, joined with a comma and a space.
I would do it this way :
respons_pre.map(function(date) { return "'" + date.toLocaleDateString() + "'"; }).join(', ');
Explanation :
map will apply a transformation to each element of the array
toLocaleDateString transform a date object to a locate string representation (if you want to force en-US format, it can be passed as a parameter)
we also add the enclosing single quotes in the transformation function
finally we join the elements of the resulting string array with a comma and a space
response_pre =response[0].s_date;
responseArr = response_pre.split(", ");
responseArrWithQuotes = responseArr.map(function(dateString) {
return "\'" + dateString + "\'";
});
responseString = responseArrWithQuotes.toString();
responseString is the result you're looking for.
Please do note that my answer demands that the string response_pre separates the dates with ,, (comma and space), not only a comma.
I have a confirmation pop-up dialog in which I am passing a variable which is a comma separated string.
How can I replace the commas and introduce a line break?
I tried using replace. I tried passing '\n' separated list from back-end. But nothing seems to work — though a normal confirm() used for testing purposes is working fine.
var listcontrol = document.getElementById(id3);
var List = listcontrol.innerText;
var finallist = List.replace("\n", "\n");
if (checkboxCell.checked == false) {
if (labelCell.innerText == "Yes") {
confirm("The selected exam is present in the following certifications: " + "\n" + finallist + "\n" +
"Uplanning this exam here would unplan the same exam under other certification(s) also.");
}
}
In your code you are replacing "\n" with "\n", which would make no difference. You want to replace "," with "\n" instead, right?
var string = "Demetrius Navarro,Tony Plana,Samuel L. Jackson";
alert(string);
alert(string.replace(/,/g, "\n"));
Live test - http://jsfiddle.net/9eZS9/
Js replace is,
string.replace(searchvalue,newvalue)
var finallist = List.replace(/,/g, "\n");
If your "pop-up dialog" is a custom html/css-based dialog then newline characters would be treated (more or less) the same as space characters. You'd need to use <br> elements instead, so:
var finallist = List.replace(/,/g, "<br>");
Note the use of the regex as the first argument for replace() - this is needed in order to do a global replace.
For use in a standard confirm you'd need newline characters like you were doing, but with a regex rather than a string for the replace() search term:
var finallist = List.replace(/,/g, "\n");