New line break every two words in javascript string - javascript

I have one string
string = "example string is cool and you're great for helping out"
I want to insert a line break every two words so it returns this:
string = 'example string \n
is cool \n
and you're \n
great for \n
helping out'
I am working with variables and cannot manually do this. I need a function that can take this string and handle it for me.
Thanks!!

You can use replace method of string.
(.*?\s.*?\s)
.*?- Match anything except new line. lazy mode.
\s - Match a space character.
let string = "example string is cool and you're great for helping out"
console.log(string.replace(/(.*?\s.*?\s)/g, '$1'+'\n'))

I would use this regular expression: (\S+\s*){1,2}:
var string = "example string is cool and you're great for helping out";
var result = string.replace(/(\S+\s*){1,2}/g, "$&\n");
console.log(result);

First, split the list into an array array = str.split(" ") and initialize an empty string var newstring = "". Now, loop through all of the array items and add everything back into the string with the line breaks array.forEach(function(e, i) {newstring += e + " "; if((i + 1) % 2 = 0) {newstring += "\n "};})
In the end, you should have:
array = str.split(" ");
var newstring = "";
array.forEach(function(e, i) {
newstring += e + " ";
if((i + 1) % 2 = 0) {
newstring += "\n ";
}
})
newstring is the string with the line breaks!

let str = "example string is cool and you're great for helping out" ;
function everyTwo(str){
return str
.split(" ") // find spaces and make array from string
.map((item, idx) => idx % 2 === 0 ? item : item + "\n") // add line break to every second word
.join(" ") // make string from array
}
console.log(
everyTwo(str)
)
output => example string
is cool
and you're
great for
helping out

Related

jQuery Replace Second Space of Sentence

I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.

How to remove the extra spaces in a string?

What function will turn this contains spaces into this contains spaces using javascript?
I've tried the following, using similar SO questions, but could not get this to work.
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
Is there a simple pure javascript way to accomplish this?
You're close.
Remember that replace replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
string.replace(/\s+/g, ' ').trim()
Try this one, this will replace 2 or 2+ white spaces from string.
const string = " this contains spaces ";
string.replace(/\s{2,}/g, ' ').trim()
Output
this contains spaces
I figured out one way, but am curious if there is a better way...
string.replace(/\s+/g,' ').trim()
I got the same problem and I fixed like this
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
I think images always explain it's good, basically what you see that the regex \s meaning in regex is whitespace. the + says it's can be multiply times. /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). and the trim will remove the last and first whitespaces if exists.
Finally, To remove extra whitespaces you will need this code:
newString = string.replace(/\s+/g,' ').trim();
We can use the below approach to remove extra space in a sentence/word.
sentence.split(' ').filter(word => word).join(' ')
Raw Javascript Solution:
var str = ' k g alok deshwal';
function removeMoreThanOneSpace() {
String.prototype.removeSpaceByLength=function(index, length) {
console.log("in remove", this.substr(0, index));
return this.substr(0, index) + this.substr(length);
}
for(let i = 0; i < str.length-1; i++) {
if(str[i] === " " && str[i+1] === " ") {
str = str.removeSpaceByLength(i, i+1);
i = i-1;
}
}
return str;
}
console.log(removeMoreThanOneSpace(str));
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string
for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
// Here my solution
const trimString = value => {
const allStringElementsToArray = value.split('');
// transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']
const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
// Remove all blank spaces from array
const finalValue = allElementsSanitized.join('');
// Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'
return finalValue;
}
I have tried regex to solve this problem :
let temp=text.replace(/\s{2,}/g, ' ').trim()
console.log(temp);
input="Plese complete your work on Time"
output="Please complete your work on Time"
//This code remove extra spaces with out using "string objectives"
s=" This Is Working On Functions "
console.log(s)
final="";
res='';
function result(s) {
for(var i=0;i<s.length;i++)
{
if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){
final+=s[i];
}
}
console.log(final);
}
result(s);

get detailed substring

i have a problem i'm trying to solve, i have a javascript string (yes this is the string i have)
<div class="stories-title" onclick="fun(4,'this is test'); navigate(1)
What i want to achieve are the following points:
1) cut characters from start until the first ' character (cut the ' too)
2) cut characters from second ' character until the end of the string
3) put what's remaining in a variable
For example, the result of this example would be the string "this is test"
I would be very grateful if anyone have a solution.. Especially a simple one so i can understand it.
Thanks all in advance
You can use split() function:
var mystr = str.split("'")[1];
var newstr = str.replace(/[^']+'([^']+).*/,'$1');
No need to cut anything, you just want to match the string between the first ' and the second ' - see similar questions like Javascript RegExp to find all occurences of a a quoted word in an array
var string = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var m = string.match(/'(.+?)'/);
if (m)
return m[1]; // the matching group
You can use regular expressions
/\'(.+)\'/
http://rubular.com/r/RcVmejJOmU
http://www.regular-expressions.info/javascript.html
If you want to do the work yourself:
var str = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (str[i] == '\'') {
while (str[++i] != '\'') {
newstr += str[i];
}
break;
}
}

Split by Caps in Javascript

I am trying to split up a string by caps using Javascript,
Examples of what Im trying to do:
"HiMyNameIsBob" -> "Hi My Name Is Bob"
"GreetingsFriends" -> "Greetings Friends"
I am aware of the str.split() method, however I am not sure how to make this function work with capital letters.
I've tried:
str.split("(?=\\p{Upper})")
Unfortunately that doesn't work,
any help would be great.
Use RegExp-literals, a look-ahead and [A-Z]:
console.log(
// -> "Hi My Name Is Bob"
window.prompt('input string:', "HiMyNameIsBob").split(/(?=[A-Z])/).join(" ")
)
You can use String.match to split it.
"HiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g)
// output
// ["Hi", "My", "Name", "Is", "Bob"]
If you have lowercase letters at the beginning it can split that too. If you dont want this behavior just use + instead of * in the pattern.
"helloHiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g)
// Output
["hello", "Hi", "My", "Name", "Is", "Bob"]
To expand on Rob W's answer.
This takes care of any sentences with abbreviations by checking for preceding lower case characters by adding [a-z], therefore, it doesn't spilt any upper case strings.
// Enter your code description here
var str = "THISSentenceHasSomeFunkyStuffGoingOn. ABBREVIATIONSAlsoWork.".split(/(?=[A-Z][a-z])/).join(" "); // -> "THIS Sentence Has Some Funky Stuff Going On. ABBREVIATIONS Also Work."
console.log(str);
The solution for a text which starts from the small letter -
let value = "getMeSomeText";
let newStr = '';
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === value.charAt(i).toUpperCase()) {
newStr = newStr + ' ' + value.charAt(i)
} else {
(i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
}
}
return newStr;

Display only whole word using javascript

I have a text say "A sample text for testing". I need to display only ten characters in a div.
so i do substring on the text
txt.substring(0,10)
This gives me "A sample t". Since its ugly to display a unterminated word, i need only to display "A Sample" to be displayed. How do i do this?
You could do what you do, substringing the text to 10 chars.
Then you use txt.lastIndexOf(' ') to find the last space in the text.
Then you use that to substring the text again.
Example:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
Let me know if it helps!
Assuming that you'd rather have a cut off string than an empty string, if the word is longer than ten characters:
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}
use substring method to do this
i think you should add a filter to check whether the 11th character is space or not with the substring method. otherwise the last valid word too might removed. get "New sample text for testing" for example.
this is the code.
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}
function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}

Categories

Resources