Hi I have some text in following format,
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545 etc....
Each line break'ed into next line with "Enter". I have nearly 2000 lines of text like this. i want o display the above string to a single line like this.
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545,
686672,
683545 etc..
I think there is some tweak options in CSS for doing this. Is there a way in JavaScript to do this? Actually it is not a requirement for me, am just curious to know how it is done.
Edit:
In My text editor it looks like this,
When i try to run it, this is what i get.
Thats why i want to remove the enter, multiline.......
You can use Regular expression to remove all the linebreaks and replace them using space.
str = str.replace(/\n/g, ' ');
Here, \n will match all the line-breaks, and replace them by space
I have a simple way for this. You can do this without extra code. Just write like this -
var str = "12345,\
234234,\
234324,\
234324,\
234324,\
234234";
now just add a slash
Ok, If you don't want to use the above method then use another plan is -
take inside an array and after that use the join method
var str = [12345,
234234,
234324,
234324,
234324,
234234];
str.join(",");
If we are using ES6, Then we have an elegant way to do this using Backtick -
var str = `12345,
234234,
234324,
234324,
234324,
234234`;
Since your data is already comma separated, you can try to add "[" to the beginning and append " ].toString().replace(/\n/g," ") " to the end of your data to get a single line string like this:
[683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545].toString().replace(/\\n/g," ")
then you get:
"683101,682303,682302,682315,683581,686667,682008,683572,683573,682313,686672,683545"
I hope this helps :)
If all you want is to put those values in one line then, you can set those values as the value of a textarea field. This will allow you to read all those values into a javascript string. Afterward you can apply the regular expression that Tushar suggested.
See the code segment below:
<textarea id="content">
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545
</textarea>
Here is the javascript:
var content = $('#content').val();
var content = content.replace(/\n/g, ' ');
console.log(content);
Related
I have a string which looks like this
var dragdropMatchResponseData = '2838[,]02841[:]2839[,]02838[:]2840[,]02840[:]2841[,]02839';
I want to replace the following
1: '[,]' into ':'
2: '[.]' into ','
I tried the following
console.log(dragdropMatchResponseData.replace({ '[,]': ':', '[:]': ',' }));
and
console.log(dragdropMatchResponseData.replace('[,]', ':').replace( '[:]', ','));
but nothing helped me
I want my end result to look like
'2838:02841,2839:02838,2840:02840,2841:02839';
I don't want to add replace in multiple times, I want to do this at one time,
how can I achieve this?
Try regular expression
dragdropMatchResponseData.replace(/\[,\]/g, ':').replace(/\[:\]/g, ',')
The /g flag is to replace all the occurances within the string.
Hey It can be easily achieved using replace function of JS
var data = '2838[,]02841[:]2839[,]02838[:]2840[,]02840[:]2841[,]02839';
console.log(data.replace(/\[:]/g, ',').replace(/\[,]/g, ':'))
How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?
Example:
A variable passed from PHP as below:
"This is man.
Man like dog.
Man like to drink.
Man is the king."
I would like my result to look something like this after the JavaScript converts it:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
This will turn all returns into HTML
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169
https://stackoverflow.com/a/36524555/5042169
If your concern is just displaying linebreaks, you could do this with CSS.
<div style="white-space: pre-line">Some test
with linebreaks</div>
Jsfiddle: https://jsfiddle.net/5bvtL6do/2/
Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).
Without regex:
str = str.split("\n").join("<br />");
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
Shortest code supporting the most common EOL styles \r, \n, \r\n and using HTML5 <br>:
s.replace(/\r?\n|\r/g, '<br>')
Regardless of the system:
my_multiline_text.replace(/$/mg,'<br>');
It is also important to encode the rest of the text in order to protect from possible script injection attacks
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
This worked for me when value came from a TextBox:
string.replace(/\n|\r\n|\r/g, '<br/>');
For those of you who just want to allow max. 2 <br> in a row, you can use this:
let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');
First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br
Second line: Search for all single \r\n or \n and replace them with <br>
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm
this will help you everytime.
Not answering the specific question, but I am sure this will help someone...
If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:
var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
I had a config in PHP that was being passed in from the Controller. (Laravel)
Example: PHP Config
'TEXT_MESSAGE' => 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
Then in javascript using es6 reduce. notice I had to have two \\ or the output was not being replace correctly. Here are the parameters that are assoicated with the reduce function
previousValue (the value resulting from the previous call to
callbackfn)
currentValue (the value of the current element)
currentIndex Optional
array (the array to traverse) Optional
//p is previousVal
//c is currentVal
String.prototype.newLineReplace = function(){
return [...arguments].reduce((p,c) => p.replace(/\\n/g,c), this);
}
Here is how i used it in my script.
<script type="text/javascript">var config = #json($config);</script>
config.TEXT_MESSAGE.newLineReplace("<br />")
of course you could just called it on a javascript sring like...
let a = 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
var newA = a.newLineReplace("<br />")
//output
'From:Us<br />User: Call (1800) 999-9999<br />userID: %s'
So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.
Possible inputs might be:
\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text
Only the first and the third line should be affected by this function.
Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.
I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.
You can use the following piece of code to do that for you:
var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');
Here, $ matches end of input.
You can refer to the regular expressions guide here to find out more about regex in JS.
EDIT:
If you really need a function for this:
var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
return input.replace(rTrimRegex, '');
}
And then use it inside your code maybe like:
var str = 'my name is foo\r\n\r\n';
str = rTrim(str);
In my html page I have to split user input based on newline character.
How to get newline character using javascript?
Please see the below code :
var str=document.getElementById('nwline').value;
var lines = str.split(/\r\n|\r|\n/g);
console.log(lines);
http://jsfiddle.net/asimshahiddIT/0yog7v83/
The resume of possible duplicate is using regex does allow you to ignore the OS you're using:
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
In your case:
var splittedValues = originalTxt.split(/\r\n|\r|\n/g);
I'm trying to create a dynamic searchbar and i need help.
Right now im trying to replace a string with another string but i cant seem to succeed.
Im getting input from the user:
var location_keyword = $("#si_user_location").val();
Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.
For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.
i tried something like this but it didnt work
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
i used to do this in PHP before with expressions such as:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
and i could replace strings caseinsensetive like this, how can i do this in js?
I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.
hope i can get some help, thanks in advance! :)
best of regards,
alexander
There are two problems with the use of replace on this line:
location_keyword.replace(" ","|");
It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
It only replaces the first occurrence unless you use a regular expression with the g (global) flag.
Try this instead:
location_keyword = location_keyword.replace(/ /g, '|');
Try this:
location_keyword = location_keyword.replace(/\s+/,"|");
This should work fine:
location_keyword.replace(/ /g,"|");
Hope this helps! :)