Split string in JavaScript and detect line break
Using .split()
:
var str = `your text
that spans
multiple lines`
// Split the string on \n or \r characters
var separateLines = str.split(/\r?\n|\r|\n/g);
alert("Total number of separate lines is: " + separateLines.length);
Split a string by word and detect/include line breaks
The idea is to "normalize" whitespaces first, and then split by a space, so that newlines "stick" to the preceding word:
const text = "Aenean non odio erat.\nSuspendisse vestibulum \n \n \n vulputate\n\nnulla et mollis."
const splitText = text => text
.replace(/\\n/g, '\n')
.replace(/\s+/g, m => m.includes('\n') ? '\n ' : ' ')
.trim()
.split(' ');
console.log(splitText(text))
Split string by line breaks, keeping quoted segments
As a simplest solution, we can first mark(replace with some identifier) the line breaks
that we would not want to split at.
Then split at all other line breaks and finally replace the preserved break identifiers with line breaks again
(\n).
arr = str.replace(/("[\s\S]*?")/g, (m, cg) => {
return cg.replace(/\n/g, "LINE-BREAK-TO-PRESERVE");
})
.split('\n')
.filter(i => Boolean(i.trim()))
.map(i => i.replace(/LINE-BREAK-TO-PRESERVE/g, '\n'));
Above code should fill your purpose smoothly :)
How to detect line break and remove everything line break
There are several ways, but if you may have \r
or \n
, I'd probably use replace
with a regex:
str = str.replace(/(?:\r|\n).*$/, '');
JavaScript split a string that has new line breaks in the string
You need to split at \n
that is followed with a string of digits, a space, and a time-like string:
s.split(/\n(?=\d+ \d{2}:\d{2}:\d{2}\b)/)
See the regex demo
Details:
\n
- a newline followed with...(?=\d+ \d{2}:\d{2}:\d{2}\b)
- (a positive lookahead that only requires that the string immediately to the right meets the pattern, else fail occurs)\d+
- 1 or more digits\d{2}:\d{2}:\d{2}
- 2 digits,:
twice and again 2 diigts\b
- trailing word boundary
var s = "3708 07:11:59 INFO (username): SAVE: master:/url_path, language: en, version: 1, id: {1846518641516} \r\n908 07:11:40 INFO (username): SAVE: master:/url_path, language: en, version: 1, id: {148815184185}, ** [Content]: new: Please note the following when using this app:\r\n\r\n▪ Some text\r\n▪ Some text\r\n▪ Some text\r\n▪ Some more and more text., old: Please note the following when using this app:\r\n\r\n▪ Some text\r\n▪ Some text\r\n▪ Some text\r\n▪ Some text\r\n▪ Some text\r\n▪ Some text\r\nends here";var res = s.split(/\n(?=\d+ \d{2}:\d{2}:\d{2}\b)/);console.log(res);
check whether string contains a line break
Line breaks in HTML aren't represented by \n
or \r
. They can be represented in lots of ways, including the <br>
element, or any block element following another (<p></p><p></p>
, for instance).
If you're using a textarea
, you may find \n
or \r
(or \r\n
) for line breaks, so:
var text = $("#theTextArea").val();
var match = /\r|\n/.exec(text);
if (match) {
// Found one, look at `match` for details, in particular `match.index`
}
Live Example | Source
...but that's just textarea
s, not HTML elements in general.
How can I detect line breaks in string coming from state?
Turns out I was able to use encodeURI(this.state.note)
. Because my end goal was to pass this to a mailto:
link, the encoded return statements get translated perfectly into %0A.
How to detect line breaks in a text area input?
You can use match
on the string containing the line breaks, and the number of elements in that array should correspond to the number of line breaks.
enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;
/\n/g
is a regular expression meaning 'look for the character \n
(line break), and do it globally (across the whole string).
The ||[]
part is just in case there are no line breaks. Match will return null
, so we test the length of an empty array instead to avoid errors.
How to split newline
Try initializing the ks
variable inside your submit function.
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
var ks = $('#keywords').val().split("\n");
e.preventDefault();
alert(ks[0]);
$.each(ks, function(k){
alert(k);
});
});
});
})(jQuery);
How to detect a line break in a <p> tag and print something after it
To create a span
after the linebreak using the link provided by @Max Starkenburg this is the code that I write:
if(current.text(current.text() + ' ' + words[i]).height() > height){
current.text(current.text().split(words[i])[0] + '</span> <span class="subrayar">' + words[i]);
height = current.height();
}
With this, after add the new word, I detect the height and, if it is bigger (is in the next line), I split this word and add it again but writting the span
tags.
In the snippet below you can see all the code.
I add a class to show the span
when is in the next line.
var subrayados_offset = []; var subrayados_element = []; var subrayados_bg = [];
jQuery(document).ready(function(){ $('.subrayado').each(function(index, element) { var current = $(this); var text = current.text(); var words = text.split(' '); current.text(words[0]); var height = current.height(); for(var i = 0; i < words.length; i++){ //console.log(height+" "+words[i]+" "+current.height()+" "+words[i+1]); if (i == 0) { current.text(words[0]); } else{ if(current.text(current.text() + ' ' + words[i]).height() > height){ console.log(current.text().split(words[i])[0]); current.text(current.text().split(words[i])[0] + '</span> <span class="subrayar other_span">' + words[i]); height = current.height(); } } } $(this).html('<span class="subrayar">'+current.text()+'</span>');
//$(this).html($(this).text().replace(/(\w+|\S+)/g, '</span>$1<span class="subrayado">')); });
$('.subrayar').each(function(index, element) { subrayados_offset[index] = $(this).offset().top; subrayados_element[index] = $(this); $(this).append("<div class='subrayado_bg' style='width:100%; height:100%; background-color:red; position:absolute; top: 0; left: 0; z-index:-1;'></div>"); subrayados_bg[index] = $(this).find(".subrayado_bg"); }); });
p{width: 300px;}.subrayar{ position: relative; }.other_span{ background-color: blue !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p><span class="subrayado">Lorem ipsum dolor sit amet</span>, consectetur adipiscing elit. Curabitur ultricies ultrices enim in condimentum. Nullam sollicitudin varius enim sit amet rutrum. Nam consequat vitae dolor eu pharetra. <span class="subrayado">Morbi vestibulum felis tristique velit varius maximus.</span> Sed venenatis, velit fringilla viverra dictum, magna quam faucibus est, sed congue augue enim a sem. Cras ut tristique enim. Quisque aliquam risus vitae erat lacinia venenatis. </p>
Related Topics
Download Image as File in Typescript
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
Node.Js MySQL Query in a for Loop
How to Format Numbers in Vuejs
Reactjs - Multiple If Conditions Inside Map Function
Access a Variable Outside of .Then Function
How to Highlight Parts of an Imagemap on Mouseover
How to Toggle (Hide/Show) Sidebar Div Using Jquery
Prevent Form Redirect or Refresh on Submit
Validate Phone Number With Yup
React Native: Image Not Displaying With Dynamic/Local Uri
How to Make a Owl Carousel With Arrows Instead of Next Previous
How to Save an Image to Localstorage and Display It on the Next Page
Running Functions One After Other in React
How to Get the Index from a Json Object With Value
How to Calculate the Sum of Table Column in Angular 2+
How to Iterate Through Json Nested Objects With Ngfor
How to Simulate Mouse Click Along With Mouse Move Using JavaScript