select multiple line breaks regex - javascript

So what I am trying to do is replace one or more instances of newline with the br tag in javascript. So far I have:
description.replace(/\n/g, '<br />');
However if there is a case where there are 2/3 newlines's in a row I get 2/3 br tags. Is there a way in regex to say give me any instances of one or more newlines's in a row and replace that whole thing with one br tag so that even if I have:
\n\n\n\n\n\n\n\n\n
that would get replace with just:
<br >

You can add the + quantifier to indicate one or more matches.
description.replace(/\n+/g, '<br />');
PS: you need to read more about regular expressions, this was fairly straight forward.

description.replace(/\n+/g, '<br />');
happy homework

Related

Escape hyphen in javascript variable

The content of variable originalText= "Pending - Submitted for Initial Review"; However when I hover over the div, the tooltip text is truncated after hypen. I have tried escaping the hypen but it's not letting me do it. It always shows the truncated text.
$('#study_header').append('<img src="images/Infow.png" class="tooltip" title=' + originalText + '/>');
If anyone knows the solution pls let me know.
After hovering it shows up as below in the source code of the browser:
<img src="images/Infow.png" class="tooltip" title=" Pending" -="" submitted="" for="" initial="" review ="">
Thank you.
You're missing quotation marks around the value of the title attribute. You can see it's treating the words in originalText as additional attributes.
You can sort of fix the problem by changing:
'...title=' + originalText + '/>'
to (note the added " marks):
'...title="' + originalText + '"/>'
I say this will "sort of" fix it, because if originalText contains certain characters (like ") this will break again, so you really should be escaping originalText. jQuery provides methods for this.
In general you don't want to build HTML with simple string concatenation, because you'll run into escaping issues like this.

Jquery doesn't find div to append to when the variable in $('#div'+variable) contains spaces

I tried to append divs using jQuery from a function's input values but noticed that I wasn't getting anything but the main div appended to the body:
var the_key = "AAA AA"; //put here as an example
$('body').append('<div class="chart_canvas" id="div_'+ the_key +'" />');
$('#div_' + the_key).append('<div id="d3_canvas'+ the_key +'" />');
It works if the_key = "AAAAA".
My not so good attempt at adding quotation marks wasn't really successful and did end up with an error (unrecognized expression) as the quotation marks end up in the expression:
$('#div_' + "'" + the_key + "'").append('<div id="d3_canvas'+ the_key +'" />');
Is there any way that I can do this? The object that I'm reading these "the_key" values from do all contain spaces.
id values cannot have spaces in them. It's just about the only restriction on id values in HTML (other than that they must be unique).
Separately, CSS ID selectors cannot contain unescaped spaces either (because a space is a descendant combinator). But that doesn't matter because #1. :-)
Use a valid ID, and provided it doesn't have any characters that are allowed in HTML ids but not CSS ID selectors (or you properly escape those characters), concatenation without quotes will work.
A space in ID is a "problem" for jQuery. Try to Escape it:
<script>
// document.getElementById or similar
document.getElementById('AAA AA');
// document.querySelector or similar
$('#AAA\\ AA');
</script>
You could also use the attribute selector like this:
<script>
$("*[id='AAA AA']");
</script>
Spaces are not legal characters of an id attribute value in HTML.
Even though it might "work" in certain situations there is no guarantee that it always will.
console.log('test', document.getElementById('test'));
console.log('te st', document.getElementById('te st'));
console.log('jQuery test', $('#test').length);
console.log('jQuery te st', $('#te st').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test</div>
<div id="te st">te st</div>

Add multiple unique ids to an element

I need to add a second unique id to an element.
I use this to generate new ids
var id = 1;
function getNextId()
{
return ++id;
}
Then I am doing this
$('<div id="content '" + getNextId() +"'" class="span6"></div>').appendTo('.new');
But I am getting an Uncaight SyntaxError: Unexpected identifier
How can I add multiple ids where the second is a unique one?
(I am remove the first id on a click, so I'm ok with leaving #content there)
Multiple ids on an element have been discussed in here: Can an html element have multiple ids?
How can I add multiple ids where the second is a unique one?
You can't.
You can't have multiple IDs on one element. You get zero or one ID per element, and that is it. If you want to add additional things to select an element by, you can use classes.
Your syntax error is due to some very confused quotation marks; I suspect you wanted to do this:
$('<div id="content newId' + getNextId() + '" class="span6"></div>')
producing something like <div id="content newId3">, which can't work. You're not giving it two IDs, you're giving it one ID with a space in it, which is an invalid ID:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
There are two problems with your code:
'a'b isn't valid JavaScipt. Try 'a' + b
Whitespace characters aren't allowed in HTML ids. And even if they were, all characters in the id attribute would make up the ID, so you can't assign more than one ID to an element. Use a class instead.
Looks like:
$('<div id="content '+ newId + getNextId() +'" class="span6"></div>').appendTo('.new');
I bet that is more right
Try this instead:
$('<div id="content-' + getNextId() + '" class="span6"></div>').appendTo('.new');
I think a pretty good start would be to add a + there.
'<div id="id-' my_id_var '"></div>'
Just isn't going to work.
"<div id=\"id-" + getNextID() + "\"></div>"
Will work just fine, though.
Second issue, each element gets 1 ID.
The point is that an ID is given to make an element uniquely-identifiable.
Why do you want the element to be uniquely identifiable twice?
There are lots of other ways of doing this.
First, you have class.
If you are working with objects which need similar states ("selected", "news-article", "user-interactive"), use classes.
Then, you have data- attributes.
<div id="player_1"
class="player-character"
data-health="42"
data-x="320"
data-y="240"
data-speed="5"
><img src="..."
></div>
Then in JS, you could do something like:
var player_1 = document.getElementById("player_1");
player_1.dataset.health; // "42"
These values are supported as far back as IE8, I think.
If you want to go further than that, then instead of using .dataset, you use .setAttribute("data-" + field_name, value)
If you're using jQuery, then it handles ALL of that for you, anyway.
So with all of these options, why do you want 2 ids per one element?

how to process textarea multiple line input if user hit "enter/return" key

my coding:
...
<textarea name="TextArea1" id="TextArea" style="height ; width" ></textarea>
...
<script type="text/javascript">
var txt_element = document.getElementById("TextArea");
document.write (txt_element.childNodes[0].nodeValue);
</script>
...
but it doesn't recognize "enter/return" key hited instead it shows " "
Many thanks
To expand on Chris's answer, the problem is that the browser is rendering the text you write in the same way as it renders any other piece of html, which means white space (including carriage returns) is treated as a word separator, not a line or paragraph separator. And multiple consecutive white space characters are condensed down to a single space. This is explained further in the html spec.
This is different to how it treats text within a textarea element.
So as Chris suggested, you need to replace carriage returns in your string with html <br> elements:
var enteredText = document.getElementById("TextArea").value;
var updatedText = enteredText.replace(/\n/g, '<br />');
document.write(updatedText);
Note: you should be able to get the textarea's value directly with .value rather than saying .childNodes[0].nodeValue.
Note 2: I second what Chris said about document.write() - it is usually not the best option.
Note 3: If you're catering for non-Windows system you may also need to replace \r.
Text areas use \n to designate a new line, something along these lines should work:
string = document.getElementById("TextArea")childNodes[0].nodeValue;
string = string.replace(/\n/g, '<br />');
document.write('string');
Not sure if you're just goofing around, but I feel compelled to mention that generally speaking you should never use document.write().

escape less / greater than javascript

I'm having a problem trying to escape some code... Basically, I want to escape "<" and ">" but I want them to APPEAR in my #output div as "<" and ">". Currently, they appear as as "<" and ">" on the page.
This is obviously to prevent anyone exploiting / injecting scripts on the page. This is my code:
var textval = $("#textarea").val(); //textarea
filtered = textval.replace(/</gi,"<"); //replace "<"
$("#output").html(filtered); //insert textarea data into div
Can anybody spot what I am doing wrong, or are there any better ways of doing this?
Many thanks
EDIT: I do want SOME html tags (like <b> to work, so I can't use $.text(); unfortunately..)
Try this:
var textval = $("#textarea").val();
$("#output").text(textval);
jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)
A little different replace, but works for me (even with .html()).
Demo
var str = $('#textarea').val();
$('#result').html(str.replace(/<|>/ig,function(m){
return '&'+(m=='>'?'g':'l')+'t;';
}));
<textarea id="textarea">
Hello, <b>World</b>!
</textarea>
<div id="result"></div>
(This is just to verify it can be done, .text() is the better approach)

Categories

Resources