I started something that appeared pretty easy, but it worked out differently.
I have this string, read from a file:
"columns:[
{
allowNull:false,
I want to replace the newline with a newline and a double-quote.
so I do:
text = text.replace(/\r?\n/g, '\n"')
somehow, the output is this:
"columns:[
\"{
\"allowNull:false,
I'm completely puzzled as to where the extra '\' is coming from. If I use a single-quote, or another character, it works just fine
What is going on here?
Within here
text = text.replace(/\r?\n/g, '\n"')
you replace with \n" instead of \n. As #vlaz indicates correctly in the comments, text.replace does not escape " to \". But the print function does.
Anyway, there's a " which may be not intended.
Related
I have a string in C# that contains an error message. This message could contain single quotes or double quotes or both, but I am free to manipulate the string however I need (as well as the HTML/Javascript).
For example, the following messages could be displayed (content isn't important, just the fact they could contain single or double quotes):
The following error has occurred: "You dun goofed."
The specified path isn't valid.
The following error has occurred: "I'm a goof"
This string is inserted into HTML as an alert inside of an onClick handler. That sounds complicated so let me show what I mean:
<a onClick="alert('myContentGoesHere')">View Error</a>
I'm able to get the single quotes to display by replacing ' with \' in C#. However, my attempts to similarly escape " has resulted in an odd number of backslashes which terminates the onClick attribute and causes invalid HTML.
So far I have tried to replace " with:
\"
\\"
"
\"
No dice. I feel like I might be approaching this from the wrong angle so if you have a solution which goes beyond a string replace, I'm all ears. Thanks for any help you can offer.
To make the value work as a string literal in JavaScript you need to escape the string delimiter and backslashes. Then you need to HTML encode the JavaScript so that it works as a value in the HTML attribute.
Example:
string code =
"<a onClick=\"" +
HttpUtility.HtmlEncode(
"alert('" +
myContentGoesHere.Replace("'", "\\'").Replace("\\", "\\\\") +
"');"
) +
"\">View Error</a>";
If the string can contain control characters, you would need to replace them too. Add the ones that you need from:
.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\b", "\\b")
.Replace("\t", "\\t")
.Replace("\v", "\\v")
.Replace("\f", "\\f")
I have a string with a line-break in the source code of a javascript file, as in:
var str = 'new
line';
Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.
Thanks in advance!
EDIT (2021)
This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.
What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.
However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.
The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:
var str = `new
line`;
is totaly valid and would be identical to
var str = 'new\n line';
As far as removing the newlines goes, I think the answers below address that issue adequately.
If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');
str = str.replace(/\n|\r/g,'');
Replaces all instances of \n or \r in a string with an empty string.
I have a text pattern that I am trying to replace in a node.js application. The pattern is:
***
some text
***
It is created in javascript with the following code:
var textblock = "***" + '\n' + 'some text' + '\n' + "***" + 'the rest of the text block'
The following regular expression works in regexpal and seems correct to me:
\*{3}\n.+\n\*{3}
But when I put it in my javascript code, it fails:
textblock.match(/\*{3}\n.+\n\*{3}/) // returns null
I tested, and even just *{3}\n doesn't seem to work. Am I missing something idiosyncratic about how javascript handles \n ? I've tried /m as well, and I've also tried [\n\r].
Thanks!
UPDATE: turns out that the GitHub API markdown processes issue body text and eliminates newlines. So my regex was correct, but I was wrong about the text I was matching in.
Try changing textblock to t:
var t = "***" + '\n' + 'some text' + '\n' + "***";
alert(t.match(/\*{1}\n.+\n\*{1}/));
(fiddle; removed some * from the regexp to check if it is working properly).
It might be an issue with line-endings. If you match for [\n\r] instead of just \n it works OK.
Here is a fiddle to demonstrate: http://jsfiddle.net/xD8a5/
The text I'm finding and replacing comes from a GitHub issue fetched via API. Turns out that when you put multiple asterisks in a row, they omit the newline chars before and after since they convert it into a graphical line.
The answer was to not require actual newline characters. This worked:
match(/\*{3}[\n\r]*.+[\n\r]*\*{3}/)
Thanks everyone for your help!
Use \\n instead of \n i tried on my code and it is working fine
through queries to a Database I am retrieving such data that I previously inserted through HTML textarea or input. When I get the response from my DB , in a JSON object the text field looks like this :
obj : {
text : [some_text] ↵ [some_text]
}
I tried to replace with this function :
string_convert = function(string){
return string.replace("↵",'<br>')
.replace('&crarr','<br>')
.replace('/[\n\r]/g','<br>');
}
I have to show this string in HTML ,but it does not seems to work. I'm using UTF-8
Any advice?
The problem you have is that you have enclosed your regex in quotes. This is incorrect.
.replace('/[\n\r]/g','<br>');
^ ^
remove these two quotes
The quotes are unnecessary because the regex is already delimited by the slashes.
By putting quotes in there, you've actually told it that you want to replace a fixed string rather than a regular expression. The fixed string may look like an expression, but with the quotes, it will just be seen as a plain string.
Remove the quotes and it will be seen as an expression, and it will work just fine.
One other thing, though -- in order to make your regex work perfectly, I'd also suggest modifying it slightly. As it stands, it will just replace all the \n and \r characters with <br>. But in some cases, they may come together as a \r\n pair. This should be a single line break, but your expression will replace it with two <br>s.
You could use an expression like this instead:
/\r\n|\n|\r/g
Hope that helps.
you are missing the ending semicolons ; in your code:
string_convert = function(aString){
return aString.replace("↵",'<br>').replace('↵','<br>');
}
this does not necessary solve your problem, but it could likely.
From: Trying to translate a carriage return into a html tag in Javascript?
text = text.replace(/(\r\n|\n|\r)/g,"<br />");
currently I am trying to highlight elements on a page. Therefore I pass a comma seperate String to a Javascript-Funktion called highlight.
highlight("main:box1,main:box2");
This was working fine till I found ids with : on the page. So I tried to escape them with a little regex. Here things started to get a little funny.
If I escape the string by replacing : with \: the jQuery-Function does not work anymore.
var string = value.replace(/:/g, "\\\\:");
jQuery("#" + string).css("color", "red");
If I replace main: with "" and write main\: in the jQuery-Function everything works fine.
var string = value.replace(/main:/g, "");
jQuery("#main\\:" + string).css("color", "red");
What am I doing wrong? Why does the jQuery-Function not except my escaped string?
Help needed :-(
Example-Code attached: http://db.tt/0FLRlM
Thanks Jan
You're double escaping the \ in your first attempt at substitution. What you've done is replace : with \\:, even though you're probably seeing \: when you output it.