I have a long text area comment given as input by user. In order that it should be properly wrapped in my JSP, I'm using the below code. commentarea is my text area:
function addNewlines(commentarea) {
var result = '';
while ($.trim(commentarea).length > 0) {
result += $.trim(commentarea).replace(/[\s\n\r]+/g, ' ').substring(0, 40) + '\n'; commentarea= $.trim(commentarea).replace(/[\s\n\r]+/g, ' ').substring(40);
}
return result;
}
The text is getting wrapped but the problem is I'm getting white spaces between words that are at 40 character length. For example, in my output I'm getting a space between
prog rammable and sim ple
hello world today this is a simple prog rammable hello world today this is a sim ple prog rammable
orelse you better to use 'word-wrap' instead of that....refer this
This
You don't need any loops to replace all spaces and line breaks by a single space.
commentarea.value = commentarea.value.replace(/\s+/g, ' ').substring(0, 40);
Related
I'm a python programmer and in Python, the \n renders a new line like so:
print("Hello \n World")
Hello
World
But I'm trying to do that in Javascript with the following block of code:
if (userInput == wrongAnswer){
let finalScore = initialScore + scoreForA;
console.log(finalScore);
if (finalScore == 5){
console.log(rightScore);
}
else{
console.log("Initial score:", initialScore, "\n", outputA, "\n", "Final score:", finalScore);
}
}
Edit: By the way, I've defined these variables already.
But it gives me:
And I'm supposed to make it:
Is the \n supposed to auto-indent Wrong answer and Final score after making a new line in JavaScript?
Note that you're providing multiple arguments to console.log, so the python analog would be print("Hello\n", "World") which would add a space on the second line as well. Multiple arguments are always separated by a space, if you don't like that, concatenate them or use a template literal:
console.log(`Initial score: ${initialScore}\n${outputA}\nFinal score:${finalScore}`)
I think it is because the function console.log() adds a space between each params.
You can do that :
console.log("Initial score" + 5 +"\n" + "WrongAnswer" +" :(" + "\n" + "Final score -1");
I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.
World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.
I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)
How do I turn this text:
• Ban Ki-moon calls for immediate ceasefire• Residents targeted in
al-Qusayr, witnesses tell HRWIsrael ignoring expanding violence by
settlers, EU reports9.18am: Footage from activists suggests that
opposition forces continue to resist government troops.This footage...
into this text:
Ban Ki-moon calls for immediate ceasefire. Residents targeted in
al-Qusayr, witnesses tell HRW. Israel ignoring expanding violence by
settlers, EU reports. 9.18am: Footage from activists suggests that
opposition forces continue to resist government troops. This
footage...
This needs to be fixed with javascript (multiple .replace commands are possible)
"• " has to be removed and replaced by a ". ", however the first "• " should just be removed
If there is no space after a dot ".", a space must be added (.This footage)
If there is no space before a time (9.18am), a space must be added
If there is no space before a capital letter (HRWIsrael) that is
followed by non-capital letters, then a dot and space ". " must be added in front
of that non-capital letter.
Breaking down into several replace statements (as listed below) is the way I would go about it (working fiddle).
The fixBullets function will turn all bullets into HTML Entities and the fixBulletEntities fixes those. I did this to normalize bullets as I'm not sure if they are just bullet characters or HTML entities in your source string.
The fixTimes function changes "9.18am:" into " 9:18am. " (otherwise, the fixPeriods function makes it look like " 9. 18am" which I am sure you do not want.
One major caveat regarding the fixCapitalsEndSentence function... This will also convert strings like "WOrDS" into "WO. rDS" which may not be what you want.
At the least, this should get you started...
function fixBullets(text) {
var bullets = /•/g;
return text.replace(bullets, '•');
}
function fixBulletEntities(text) {
var bulletEntities = /•/ig;
text = text.replace(bulletEntities, '. ');
if (text.indexOf('. ') === 0) {
text = text.substring(2);
}
return text;
}
function fixTimes(text) {
var times = /(\d+)[\.:](\d+[ap]m):?/ig;
return text.replace(times, ' $1:$2. ');
}
function fixPeriods(text) {
var periods = /[.](\w+)/g;
return text.replace(periods, '. $1');
}
function fixCapitalsEndSentence(text) {
var capitalsEndSentence = /([A-Z]{2,})([a-z]+)/g;
text = text.replace(capitalsEndSentence, function(match1, match2, match3) {
var len = match2.length - 1;
var newText = match2.substring(0, len) + '. ' + match2.substring(len, len + 1) + match2.substring(len + 1) + match3;
return newText;
});
return text;
}
function fixMultipleSpaces(text) {
var multipleSpaces = /\s+/g;
return text.replace(multipleSpaces, ' ');
}
function fixAll(text) {
text = fixBullets(text);
text = fixBulletEntities(text);
text = fixTimes(text);
text = fixPeriods(text);
text = fixCapitalsEndSentence(text);
text = fixMultipleSpaces(text);
return text;
}