Convert Multiple Spaces to At Beginning of Line with Javascript - javascript

I'm working on a text input for the backend of a website. I want a couple things to be automatically corrected. Example, new lines in the textarea I convert to <br>. I also want to let the user tab over on new lines.
This requires changing spaces over to . I only want to convert spaces that are at the start of a new line though. Example, say the user types this into a textarea:
This is my text! It's pretty great.
This is a second line.
This is a third line, that is indented by four spaces.
This is a fourth line.
Using regex, I've gotten the first space on each line to convert:
.replace(/^[ ]/mg,' ');
I've gotten multiple spaces to convert to one space:
.replace(/[ ]{2,}/mg,' ');
I can't figure out how to convert all four of those indenting spaces though. I've been scouring the internet for about 3 hours, and I've found similar answers, but nothing that I could get to work here. Any thoughts?

function escapeSpaces(str) {
var regex = /^ +/mg;
return str.replace(regex, function (match) {
var result = "";
for (var i = 0, len = match.length; i < len; i++) {
result += " ";
}
return result;
});
}
This may not be the best solution, but it works.
Alternatively:
function escapeSpaces (str) {
return str.replace(/^ +/mg, function (match) {
return match.replace(/ /g, " ");
});
}

Related

How can I split a string in JavaScript after the first space after 15 characters?

I have read the solution on this post How do I split a string at a space after a certain number of characters in javascript?
And it works to a certain point. But what I am trying to achieve is slightly different.
I have a user input which has a 40 character limit. I am taking that input and displaying it on the screen. However, I need to split the input at around 20 characters and then insert the remainder on the next line. And it is only allowed to go on 2 lines max.
UPDATE:: I should also mention here that as well as displaying the text on the front end, we also need to pass the string to our backend. But instead of sending it with the <br/>, we need to insert \n to force the new line in our backend system.
Ultimately, each line cannot be over 20 characters. However, it needs to be dynamic, so that if the user inputs a string that is 30 characters, but the space comes before the 20th character, how can I adjust it so that it splits at a space before the 20th character? - I hope that makes sense.
For example
TEXT12345 STRING46789
Should appear like this
TEXT12345
STRING46789
but, also the following
TEXT STRING ABCDEF
NEW LINE HERE
Each line needs to be a maximum of 20 characters and I can't force hyphenation.
The below code is what I have done, but it doesn't work well as I often get 'undefined' before the space. Plus, its not dynamically looking for a space before the 20 character limit
Child1Name.keyup(function(e) {
var stringValue = Child1Name.val();
if (stringValue.length > 19) {
let [firstLine, secondLine] = stringValue.replace(/.{20}\S*\s+/g, "$&#").split(/\s+#/)
previewChild1Name.html(firstLine + "<br/>" + secondLine);
}else{
previewChild1Name.text(stringValue);
}
});
Any help here would be greatly appreciated.
You can write a function like below. First split your string with space and loop over it to append the word. If after appending a new word it surpasses the length then add existing word to arr and clear the current string.
Try the code below.
function getSplittedString(s, length) {
let arr = [];
let str = '';
s.split(' ').forEach(x => {
if (str !== '' && (str + ' ' + x).length > length) {
arr.push(str);
str = '';
}
str = (str + ' ' + x).trim();
});
if (str !== '') {
arr.push(str);
}
return arr.join('<br/>')
}
console.log(getSplittedString('TEXT12345 STRING46789', 20));
from what i have seen and found on this site:
mdn website
You can use split(on strings) like this on stringvalue(should be the entire string);
var stringvalue = 'TEXT12345 STRING46789';
var words = str.split(' '); // what charater need to cut the string
console.log(words[0]);
// expected output: "TEXT12345"
Sorry for the rushing the answer, kinda busy rn Hope this helps.

js Split array add space between words (not first)

I have a string Topic: Computer Science
And want to strip out topic: (but in fact I want this to work with any header on the string line) and return Computer Science.
I thought about splitting the components and then adding the spaces back in:
var subjectLine = thisLine.split(" ");
var subjectString = "";
for (i = 1; i < subjectLine.length; i++) {
subjectString += subjectLine[i] + " ";
}
But then I need to remove the last space from the string.
For each doesn't work as I need to NOT have the first element appended.
I'm not sure how to do this in js so it is reusable for many different lines and topic names that can come from the subjectLine
After splitting the line, remove the first element from the array, then join the rest back together.
var thisLine = "Topic: Computer Science";
var subjectLine = thisLine.split(" ");
subjectLine.splice(0, 1);
var subjectString = subjectLine.join(" ");
console.log(subjectString);
You might consider using a regular expression, it'll probably be a lot easier than working with arrays: match the non-space characters at the beginning of the string, followed by at least one space, and .replace with the empty string:
const subjectString = thisLine.replace(/^\S+\s+/, '');
const transform = line => line.replace(/^\S+\s+/, '');
console.log(transform('Topic: Computer Science'));
You need to know where the heading stops and the real data starts. Then delete all characters up to that point.
So, for instance, if you know that the heading ends with a colon, then do:
var line = "this is the topic: Computer Science";
var topic = line.replace(/^.*:\s*/, "");
console.log(topic);

JavaScript replace all but last whilst preserving original line breaks

I have some code which outputs as follows:
function replaceAllButLast(str, splitRegex, pOld, pNew) {
var parts = str.split(splitRegex)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var str = "fred\r\nfred\r\nfred\r\n"
var desiredResult = replaceAllButLast(str, /(?:\r?\n|\r)/, '\n', '\n+')
console.log(desiredResult)
The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it with \n
However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)
Does anyone have some code that would give the same output as the code here BUT will preserve the original line break characters whilst still adding the + after a newline (except on the last line).
I am using pure vanilla JavaScript.
PS I must use the regex /(?:\r?\n|\r)/
PPS There is no need to use .split().
This will keep the last newline as it is but others added a +, see replace
var str = "fred\r\nfred\r\nfred\r\n";
var splitRegexp = new RegExp(/(?:\r?\n|\r)/, 'g')
var newstr = str.replace(splitRegexp, function(match, offset, string) {
var follow = string.slice(offset);
var isLast = follow.match(splitRegexp).length == 1;
if (!isLast) {
return match + '+';
} else {
return match;
}
})
console.log(newstr)
I've replaced your regexp with visible chars so you can see what's going on:
var input = "fredEOLfredENDLfredFINfred";
input = input.replace(/(EOL|ENDL|FIN)/g, "$1+");
console.log(input);

Split in to Sentences and Wrap With Tags

I'm trying to build a text fixing page for normalising text written in all capital letters, all lower case or an ungrammatical mixture of both.
What I'm currently trying to do is write a regular expression to find all full stops, question marks and line breaks, then split the string in to various strings containing all of the words up to and including each full stop.
Then I'm going to wrap them with <span> tags and use CSS :first-letter and text-transform:capitalize; to capitalise the first letter of each sentence.
The last stage will be writing a dictionary function to find user-specified words for capitalisation.
This question only concerns the part about writing a regex and splitting in to strings.
I've tried too many methods to post here, with varying results, but here's my current attempt:
for(var i=0; i < DoIt.length; i++){
DoIt[i].onclick = function(){
var offendingtext = input.value.toString();
var keeplinebreaks = offendingtext.replace(/\r?\n/g, '<br />');
var smalltext = keeplinebreaks.toLowerCase();
//split at each character I specify
var breakitup = smalltext.split(/[/.?\r\n]/g);
breakitup.forEach(function(i){
var i;
console.log(i);
var packagedtogo = document.createElement('span');
packagedtogo.className = 'sentence';
packagedtogo.innerHTML = breakitup[i];
output.appendChild(packagedtogo);
i++;
});
}
}
It was splitting at the right places before, but it was printing undefined in the output area between the tags. I've been at this for days, please could someone give me a hand.
How can I split a string in to multiple string sentences, and then wrap each string with html tags?
Your regex for the split is fine. Just forgot to escape a few characters:
var str = "SDFDSFDSF?sdf dsf sdfdsf. sdfdsfsdfdsfdsfdsfdsfsdfdsf sdf."
str.split( (/[\.\?\r\n]/g))
//["SDFDSFDSF", "sdf dsf sdfdsf", " sdfdsfsdfdsfdsfdsfdsfsdfdsf sdf", ""]
Use for each iteration capabilities like this:
breakitup.forEach(function(element){
var packagedtogo = document.createElement('span');
packagedtogo.className = 'sentence';
packagedtogo.innerHTML = element;//breakitup is undefiend
output.appendChild(packagedtogo);
//No need to increase index
});

splitting a string in js where a pattern DOES NOT match?

i am trying to split a TextArea value where a pattern does not match
the text is like following:
Some Good Tutorials
http://a.com/page1
http://a.com/page2
Some Good Images
http://i.com/p1
http://i.com/p2
Some Good Videos
http://m.com/p1
http://m.com/p2
now i want to get only the links from the text so a better solution would be to split the whole string in an array of strings where the a line is not a url and then from amongst this array split each string with "\n"
edit:
okay i found a solution, i can find lines which does not begin with http:// or https:// and replace them with a good place holder after than i can get the links
though i am weak in regex so can someone tell me how to do this in javascript?
Match the pattern. don't split with it.
value=value.match(/http\:\/\/.+/g)
(.+matches everything to the end of a line)
Solved finally! Here is the code:
function split_lines() {
var oText = $('linkTxtArea').value;
removeBlankLines(); // a helper function to remove blank lines
oText = oText.split("\n"); // first split the string into an array
for (i = 0; i < oText.length; i++) // loop over the array
{
if (!oText[i].match(/^http:/)) // check to see if the line does not begins with http:
{
oText[i] = oText[i].replace(oText[i], "!replaced!"); // replace it with '!replaced!'
}
}
oText = oText.toString().split("!replaced!"); // now join the array to a string and then split that string by '!replaced!'
for (i = 1; i < oText.length; i++)
{
oText[i] = oText[i].replace(/^,/,"").replace(/,$/,""); // there were some extra commas left so i fixed it
}
return oText;
}

Categories