I want to add some strings to a textarea which are file basenames. Everything is fine, but the only problem is that it mixes all the values and there are not any line breaks:
var file_name = file.file_name;
var base = new String(file_name).substring(file_name.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1)
base = base.substring(0, base.lastIndexOf("."));
$('textarea#image_Basename').append(base).split('\n');
These are my file basenames:
5b0cd65710052633dc5dcac406a382c4
212asaddgcvjh622sdsds22113554dfd
5sd5weea55rr6qasfdjkloijhj665s6a
But after storing the data in to the database and retrieving it, the result I get is:
5b0cd65710052633dc5dcac406a382c4212asaddgcvjh622sdsds22113554dfd5sd5weea55rr6qasfdjkloijhj665s6a
To preserve newlines that are coming from a database or whatever, replace the newline characters with the HTML entity for a line feed:
base = base.replace("\n", '
');
$('#image_Basename').append(base);
If you're trying to append each string with a newline at the end, just concatenate it onto the string:
$('#image_Basename').append(base + '
');
Also, you're using split on the textarea jQuery element, which doesn't make sense as it is an object not a string.
My Special thanks to #rink.attendant.6, his second method worked for me :) The answer is:
$('#image_Basename').append(base + '
');
After adding this, I got all the file basenames in separate lines!
Related
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'
In input field replace more than one space with one space after save button.
string = string.replace(/\s\s+/g, ' ');
It worked but it does not saved permanently into that value. I need to save permanently with one space only
Keep in mind that replace doesn't mutate the string, but rather returns a new one.
const original = 'this has double spaces';
const singleSpaced = original.replace(/\s\s+/g, ' ');
console.log('Original: ' + original)
console.log('Single-spaced: ' + singleSpaced);
My problem is how to properly format string in javascript function parameter list. Function call is created on the server, problem is with string single apostrophes.
Code (.NET, C#) (I want only element.cMEST_CDO2 in single quotes):
#"ng-click='DeleteElementFromSession(" + element.iMERC_KEY + "," + element.iACCO_KEY +
#",'" + element.cMEST_CDO2 + #"');'></i></div>";
This code is on the client visible like this (it throws error):
I would like to be like this:
EDIT:
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
I've got a 100,000+ long list of English words in plain text. I want to use split() to convert the list into an array, which I can then convert to an associative array, giving each list item a key equal to its own name, so I can very efficiently check whether or not a string is an English word.
Here's the problem:
The list is new-line separated.
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
This means that var list = ' <copy/paste list> ' isn't going to work, because JavaScript quotes don't work multi-line.
Is there any way for me to work with this 100,000 item new-line separated string?
replace the newlines with commas in any texteditor before copying to your js file
One workaround would be to use paste the list into notepad++. Then select all and Edit>Line Operations>Join lines.
This removes new lines and replaces them with spaces.
If you're doing this client side, you can use jQuery's get function to get the words from a text file and do the processing there:
jQuery.get('wordlist.txt', function(results){
//Do your processing on results here
});
If you're doing this in Node.js, follow the guide here to see how to read a file into memory.
You can use notepad++ or any semi-advanced text editor.
Go to notepad++ and push Ctrl+H to bring up the Replace dialog.
Towards the bottom, select the "Extended" Search Mode
You want to find "\r\n" and replace it with ", "
This will remove the newlines and replace it with commas
jsfiddle Demo
Addressing this purely from having a string and trying to work with it in JavaScript through copy paste. Specifically the issues regarding, "This means that var list = ' ' isn't going to work, because JavaScript quotes don't work multi-line.", and "Is there any way for me to work with this 100,000 item new-line separated string?".
You can treat the string like a string in a comment in JavaScript . Although counter-intuitive, this is an interesting approach. Here is the main function
function convertComment(c) {
return c.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
It can be used in your situation as follows:
var s = convertComment(function() {
/*
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
*/
});
At which point you may do whatever you like with s. The demo simply places it into a div for displaying.
jsFiddle Demo
Further, here is an example of taking the list of words, getting them into an array, and then referencing a single word in the array.
//previously shown code
var all = s.match(/[^\r\n]+/g);
var rand = parseInt(Math.random() * all.length);
document.getElementById("random").innerHTML = "Random index #"+rand+": "+all[rand];
If the words are in a separate file, you can load them directly into the page and go from there. I've used a script element with a MIME type that should mean browsers ignore the content (provided it's in the head):
<script type="text/plain" id="wordlist">
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
</script>
<script>
var words = (function() {
var words = '\n' + document.getElementById('wordlist').textContent + '\n';
return {
checkWord: function (word) {
return words.indexOf('\n' + word + '\n') != -1;
}
}
}());
console.log(words.checkWord('aaliis')); // true
console.log(words.checkWord('ahh')); // false
</script>
The result is an object with one method, checkWord, that has access to the word list in a closure. You could add more methods like addWord or addVariant, whatever.
Note that textContent may not be supported in all browsers, you may need to feature detect and use innerText or an alternative for some.
For variety, another solution is to put the unaltered content into
A data attribute - HTML attributes can contain newlines
or a "non-script" script - eg. <SCRIPT TYPE="text/x-wordlist">
or an HTML comment node
or another hidden element that allows content
Then the content could be read and split/parsed. Since this would be done outside of JavaScript's string literal parsing it doesn't have the issue regarding embedded newlines.
I have a string like this
"/folder1/folder2/folder3/IMG_123456_PP.jpg"
I want to use JavaScript / jQuery to replace the 123456 in the above string with 987654. The entire string is dynamic so cant do a simple string replace. For example, the string could also be
"/folder1/folder2/folder3/IMG_143556_TT.jpg"
"/folder1/folder2/folder3/IMG_1232346_RR.jpg"
Any tips on this?
"/folder1/folder2/folder3/IMG_123456_PP.jpg".replace(/\_\d{2,}/,'_987654');
Edit :
"/fo1/fo2/fol3/IMG_123456fgf_PP.jpg".replace(/\_\d{2,}[A-Za-z]*/,'_987654');
I am sure there is a better way to do this, but if you are trying to always replace the numbers of that file regardless of what they may be you could use a combination of splits/joins like this:
str = "/folder1/folder2/folder3/IMG_143556_TT.jpg" //store image src in string
strAry = str.split('/') //split up the string by folders and file (as last array position) into array.
lastPos = strAry.length-1; //find the index of the last array position (the file name)
fileNameAry = strAry[lastPos].split('_'); //take the file name and split it into an array based on the underscores.
fileNameAry[1] = '987654'; //rename the part of the file name you want to rename.
strAry[lastPos] = fileNameAry.join('_'); //rejoin the file name array back into a string and over write the old file name in the original string array.
newStr = strAry.join('/'); //rejoin the original string array back into a string.
What this will do is make it so that regardless of what directory or original name of the file name is, you can change it based on the string's structure. so as long as the file naming convention stays the same (with underscores) this script will work.
please excuse my vocab, I know it's not very good heh.
Use a regular expression
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,function($0, $1){
return $1 ? $1 + '987654' : $0;
});
example at http://www.jsfiddle.net/MZXhd/
Perhaps more comprehensible is
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var replacewith = '987654';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,'$1'+replacewith);
example at http://www.jsfiddle.net/CXAq6/