Add line breaks after n numbers of letters in long words - javascript

A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:
aaaaaaaaaaaaaaaaaaaaaaaaa
Should turn in to
aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa
I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks

Here is one option:
string.match(/.{1,10}/g).join("<br/>");

Assuming the text is inside a div or a span:
<div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div>
You can do:
$(function() {
var html=$('#myDiv').html();
var newHtml='';
for (var i=0;i<html.length;i++) {
newHtml=newHtml+html[i];
if ((i+1)%10==0) {newHtml=newHtml+'<br/>';}
}
$('#myDiv').html(newHtml);
});
Here is example: http://jsfiddle.net/68PvB/
Good Luck!

If you have your string in a variable you can use its replace method like this:
var chunklen = 2; //the length of the chunks you require
var str = '123456789'; //your string
var rxp = new RegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9

Related

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Cant make regex work to remove the first white space character

I have the following div:
<div data-test="([1] Hello World), ([2] Foo Bar)"></div>
Now what I am trying to do is to find the cleanest way to break the string into the following pieces:
array ["1", "Hello World", "2", "Foo Bar"];
How can I achieve this the proper and fast way?
I managed to get close but my solution seems somewhat ugly and doesnt work as expected.
var el = document.getElementsByTagName("div")[0];
data = el.getAttribute('data-test');
list = data.replace(/[([,]/g, '').split(/[\]\)]/);
for(str of list) {
str = str.trim();
}
I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.
The below function should work.
function strToArr(str) {
var arr = [];
var parts = str.split(', ');
parts.forEach(part => {
var digit = part.match(/(\d+)/g)[0];
var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
arr.push(digit, string);
});
return arr;
}
var text = '([1] Hello World), ([2] Foo Bar)';
var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');
var array = textReplaced.split(', ');
console.log(array);
Without any cycle.
You can try the following regular expression:
list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);
Two steps:
remove the heading "(["and tailing ")"
split the string into the parts you want with the delimiter symbols
Suppose the format of the string is fixed.

javascript regex to remove particular format text from string

I have a dynamic string and I want to remove particular format text from String. (i.e *Number)
For example: /1*Region 1/42*Europe/51*Test/100*New Folder/119*New Folder
Output : /Region 1/Europe/Test/New Folder/New Folder
Thanks in advance.
var str = "/1*Region 1/42*Europe/51*Test/100*New Folder/119*New Folder";
var regex = /(\/\d+\*)/g;
var output = str.replace( regex, '/' );
console.log( output );
An alternative solution is to search for a digit (\d+) followed by a * (\*) and replace it with nothing.
var dynamic="/1*Region 1/42*Europe/51*Test/100*New Folder/119*New Folder";
var edited=dynamic.replace(/\d+\*/g, '');
console.log(edited);
Here is another way using split and join:
var str = '/1*Region 1/42*Europe/51*Test/100*New Folder/119*New Folder',
result = str.split(/\d+\*/).join('');
console.log(result);

Find last string after delimiter: Javascript

I have a url with many delimiters '/'.
I want to find the string after the last delimiter. How can I write a javascript code?
for eg if my url is
localhost/sample/message/invitation/create/email
I want to display 'email' as my output.
var last = input.split("/").pop();
Simples!
Splitting on a regex that matches spaces or hyphens and taking the last element
var lw = function(v) {
return (""+v).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lw('This is a test.'); // returns 'test.'
lw('localhost/sample/message/invitation/create/email,'); // returns 'email,'
var url="localhost/sample/message/invitation/create/email";
url.split("/").pop()
or
var last=$(url.split("/")).last();
Usng simple regex
var str = "localhost/sample/message/invitation/create/email";
var last = str.match(/[^/]*$/)[0]";
Above regex return all character after last "/"

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories