AngularJS line break at points after a maximum length was reached - javascript

I'm using ng-repeat to fill a table. Some elements have a pretty long length, and I'm looking for a way to cut the content into multiple lines, if a specific length is reached.
During research I found Angulars limitTo, but it does not exactly look like I was looking for.
E.g. hi i'm a long description and oh, a package (org.foo.awesome.stuff) should convert into hi i'm a long description and oh,'
a package (org.foo.awesome.stuff)
Big thanks in advance.

Write a custom filter:
angular.module('filters', []).filter('lineBreaker', function() {
return function(input, breakLength) {
var newString = "";
for (var i = 0; i < input.length; i++) {
newString = newString+input[i];
if (i%breakLength == 0) {
newString = newString+"\n";
}
}
return newString;
};
});
Called like:
{{ expression | lineBreaker: 10 }}
I'm sure there is a more performant way to do this, but it will get the job done.

app.filter("break", function(){
return function(input, length){
return input.match(new RegExp(".{1," + length + "}", 'g')).join("<br/>");
}
});

You can use something like the following to insert a line break every limit characters:
var a = "hi i'm a long description and oh, a package (org.foo.awesome.stuff)";
var limit = 10;
for (var i = 0; i < a.length; i++) {
if (i % (limit + 1) === 0 && i > 0) {
a = [a.slice(0, i), '\n', a.slice(i)].join('');
}
}
console.log(a);
/** Output:
hi i'm a lo
ng descrip
tion and o
h, a packa
ge (org.fo
o.awesome.
stuff)"
*/
Throw that into a custom filter.

An easier solution would be to use CSS to modify the word-wrap of the text in the elements of a table.
e.g.
th {
word-wrap:normal;
}
td {
word-wrap:normal;
}
In addition to this, you would probably have to edit the width of your table elements so that word-wrapping will occur (instead of creating a box as long as your text). This can be simply achieved by editing the css styling as shown in the following code. There are two options (depending on if you want your webpage to be scaleable or not)
Option 1:
th {
width:300px;
}
...
Option 2:
td {
width:10%
}
...
Also noteable about this solution, it DOES NOT break the given string at any word (unless otherwise told to do so). You can read more about word-wrap here.

Related

split html text by some special tags [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have description with html format. But it need to display in one line. And at the end of line, we need to display '...' when it's too long. I tried to use css, some thing like :
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
It worked. but when I put some html tags such as p, div. It can not work any more. It displayed more than one line :(.
I tried to use javascript also, split html text by regex pattern, I used this pattern /</?[^>]+>/g, but it also remove some tags: b..., but I don't want it. i just want to remove div, br, p, table...
So could you give me some idea. Thanks.
Try split join:
"some text <br />".split("<br />").join("");
if you have variable tags you may should try something like this:
var tagString = "someText<div class='someClass'><b><h1>someText<h1><br /></b></div>";
var noTagString = "";
var lastIndex = 0;
var dontRemove = ["<b>", "</b>"];
// iterate over the tagged text
for(var i = 0; i < tagString.length; i++){
// check for '>'
if(tagString[i] === "<"){
// if '<' is found
noTagString += tagString.substring(lastIndex, i);
// take the left over
var leftOver = tagString.substr(i, tagString.length);
var goOn = false;
// check for tags to keep
for(var k = 0; k < dontRemove.length; k++){
if(leftOver.startsWith(dontRemove[k])){
goOn = true;
break;
}
}
if (goOn){
// we found a tag we want to keep so go on
continue;
}
// iterate over the left over
for(var j = 0; j < leftOver.length; j++){
// if closing tag is found
if(leftOver[j] === ">"){
// update i and last index
i = i + j;
lastIndex = i + 1;
break;
}
}
}
}
this is not tested to well but maybe it points you in the right direction.
Put the tags you want to keep in the dontRemove array.

Letters to predefined numbers conversion in one window

)
I have searched high and low, but i can´t find what i need. Or i´m to stupid to get it right ;-)
I need a page with several input boxes where i can type some text, and then an output area below each input, that shows the text converted to some predefined numbers.
example:
input: abcde fghi æøå (i need all kinds of characters like .,/: etc.)
output: 064 065 066 067 068 032
So it needs to convert like this:
"a"="064 "
"b"="065 "
"space"="032 "
(and yes, each number in output needs to be separated, or a space added after each number)
I have tried some different cipher guides in both php and javascript, but can´t get it to work. I did do an Excel document that could do some of it, but it had a limited amount of characters it could convert, then it started behaving weird. So i thought maybe PHP was the answer!
Any help is very appreciated
/Rasmus
In the spirit of elclanrs deleted answer, and for posterity:
<script>
// Using standard for loop
function stringToCharcodes(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
for (var i=0, iLen=s.length; i<iLen; i++) {
result.push(pad(s.charCodeAt(i)));
}
return result.join(' ');
}
// Using ES5 forEach
function stringToCharcodes2(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
s.split('').forEach(function(a){result.push(pad(a.charCodeAt(0)))});
return result.join(' ');
}
</script>
<input onkeyup="document.getElementById('s0').innerHTML = stringToCharcodes(this.value);"><br>
<span id="s0"></span>
Edit
If you want a custom mapping, use an object (I've only included 2 characters, you can add as many as you want):
var mapChars = (function() {
var mapping = {'198':'019', '230':'018'};
return function (s) {
var c, result = [];
for (var i=0, iLen=s.length; i<iLen; i++) {
c = s.charCodeAt(i);
result.push(c in mapping? mapping[c] : c);
}
return result.join(' ');
}
}());
alert(mapChars('Ææ')); //
Using the character code for mapping seems to be a reasonable solution, using the actual character may be subject to different page character encoding.

Searching for most performant way for string replacing with javascript

I'm programming my own autocomplete textbox control using C# and javascript on clientside. On client side i want to replace the characters in string which matching the characters the user was searching for to highlight it. For example if the user was searching for the characters 'bue' i want to replace this letters in the word 'marbuel' like so:
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
in order to give the matching part another color. This works pretty fine if i have 100-200 items in my autocomplete, but when it comes to 500 or more, it takes too mutch time.
The following code shows my method which does the logic for this:
HighlightTextPart: function (text, part) {
var currentPartIndex = 0;
var partLength = part.length;
var finalString = '';
var highlightPart = '';
var bFoundPart = false;
var bFoundPartHandled = false;
var charToAdd;
for (var i = 0; i < text.length; i++) {
var myChar = text[i];
charToAdd = null;
if (!bFoundPart) {
var myCharLower = myChar.toLowerCase();
var charToCompare = part[currentPartIndex].toLowerCase();
if (charToCompare == myCharLower) {
highlightPart += myChar;
if (currentPartIndex == partLength - 1)
bFoundPart = true;
currentPartIndex++;
}
else {
currentPartIndex = 0;
highlightPart = '';
charToAdd = myChar;
}
}
else
charToAdd = myChar;
if (bFoundPart && !bFoundPartHandled) {
finalString += '<span style="color:#81BEF7;font-weight:bold">' + highlightPart + '</span>';
bFoundPartHandled = true;
}
if (charToAdd != null)
finalString += charToAdd;
}
return finalString;
},
This method only highlight the first occurence of the matching part.
I use it as follows. Once the request is coming back from server i build an html UL list with the matching items by looping over each item and in each loop i call this method in order to highlight the matching part.
As i told for up to 100 items it woks pretty nice but it is too mutch for 500 or more.
Is there any way to make it faster? Maybe by using regex or some other technique?
I also thought about using "setTimeOut" to do it in a extra function or maybe do it only for the items, which currently are visible, because only a couple of items are visible while for the others you have to scroll.
Try limiting visible list size, so you are only showing 100 items at maximum for example. From a usability standpoint, perhaps even go down to only 20 items, so it would be even faster than that. Also consider using classes - see if it improves performance. So instead of
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
You will have this:
mar<span class="highlight">bue</span>l
String replacement in JavaScript is pretty easy with String.replace():
function linkify(s, part)
{
return s.replace(part, function(m) {
return '<span style="color:#81BEF7;font-weight:bold">' + htmlspecialchars(m) + '</span>';
});
}
function htmlspecialchars(txt)
{
return txt.replace('<', '<')
.replace('>', '>')
.replace('"', '"')
.replace('&', '&');
}
console.log(linkify('marbuel', 'bue'));
I fixed this problem by using regex instead of my method posted previous. I replace the string now with the following code:
return text.replace(new RegExp('(' + part + ')', 'gi'), "<span>$1</span>");
This is pretty fast. Much faster as the code above. 500 items in the autocomplete seems to be no problem. But can anybody explain, why this is so mutch faster as my method or doing it with string.replace without regex? I have no idea.
Thx!

Fastest way to search string in javascript

I have a hidden field on my page that stores space separated list of emails.
I can have maximum 500 emails in that field.
What will be the fastest way to search if a given email already exists in that list?
I need to search multiple emails in a loop
use RegEx to find a match
use indexOf()
convert the list to a
javascript dictionary and then
search
If this is an exact duplicate, please let me know the other question.
Thanks
EDIT:
Thanks everyone for your valuable comments and answers.
Basically my user has a list of emails(0-500) in db.
User is presented with his own contact list.
User can then choose one\more emails from his contact list to add to the list.
I want to ensure at client side that he is not adding duplicate emails.
Whole operation is driven by ajax, so jsvascript is required.
The answer is: It depends.
It depends on what you actually want to measure.
It depends on the relationship between how many you're searching for vs. how many you're searching.
It depends on the JavaScript implementation. Different implementations usually have radically different performance characteristics. This is one of the many reasons why the rule "Don't optimize prematurely" applies especially to cross-implementation JavaScript.
...but provided you're looking for a lot fewer than you have in total, it's probably String#indexOf unless you can create the dictionary once and reuse it (not just this one loop of looking for X entries, but every loop looking for X entries, which I tend to doubt is your use-case), in which case that's hands-down faster to build the 500-key dictionary and use that.
I put together a test case on jsperf comparing the results of looking for five strings buried in a string containing 500 space-delimited, unique entries. Note that that jsperf page compares some apples and oranges (cases where we can ignore setup and what kind of setup we're ignoring), but jsperf was being a pain about splitting it and I decided to leave that as an exercise for the reader.
In my tests of what I actually think you're doing, Chrome, Firefox, IE6, IE7 and IE9 did String#indexOf fastest. Opera did RegExp alternation fastest. (Note that IE6 and IE7 don't have Array#indexOf; the others do.) If you can ignore dictionary setup time, then using a dictionary is the hands-down winner.
Here's the prep code:
// ==== Main Setup
var toFind = ["aaaaa100#zzzzz", "aaaaa200#zzzzz", "aaaaa300#zzzzz", "aaaaa400#zzzzz", "aaaaa500#zzzzz"];
var theString = (function() {
var m, n;
m = [];
for (n = 1; n <= 500; ++n) {
m.push("aaaaa" + n + "#zzzzz");
}
return m.join(" ");
})();
// ==== String#indexOf (and RegExp) setup for when we can ignore setup
var preppedString = " " + theString + " ";
// ==== RegExp setup for test case ignoring RegExp setup time
var theRegExp = new RegExp(" (?:" + toFind.join("|") + ") ", "g");
// ==== Dictionary setup for test case ignoring Dictionary setup time
var theDictionary = (function() {
var dict = {};
var index;
var values = theString.split(" ");
for (index = 0; index < values.length; ++index) {
dict[values[index]] = true;
}
return dict;
})();
// ==== Array setup time for test cases where we ignore array setup time
var theArray = theString.split(" ");
The String#indexOf test:
var index;
for (index = 0; index < toFind.length; ++index) {
if (theString.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The String#indexOf (ignore setup) test, in which we ignore the (small) overhead of putting spaces at either end of the big string:
var index;
for (index = 0; index < toFind.length; ++index) {
if (preppedString.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The RegExp alternation test:
// Note: In real life, you'd have to escape the values from toFind
// to make sure they didn't have special regexp chars in them
var regexp = new RegExp(" (?:" + toFind.join("|") + ") ", "g");
var match, counter = 0;
var str = " " + theString + " ";
for (match = regexp.exec(str); match; match = regexp.exec(str)) {
++counter;
}
if (counter != 5) {
throw "Error";
}
The RegExp alternation (ignore setup) test, where we ignore the time it takes to set up the RegExp object and putting spaces at either end of the big string (I don't think this applies to your situation, the addresses you're looking for would be static):
var match, counter = 0;
for (match = theRegExp.exec(preppedString); match; match = theRegExp.exec(preppedString)) {
++counter;
}
if (counter != 5) {
throw "Error";
}
The Dictionary test:
var dict = {};
var index;
var values = theString.split(" ");
for (index = 0; index < values.length; ++index) {
dict[values[index]] = true;
}
for (index = 0; index < toFind.length; ++index) {
if (!(toFind[index] in dict)) {
throw "Error";
}
}
The Dictionary (ignore setup) test, where we don't worry about the setup time for the dictionary; note that this is different than the RegExp alternation (ignore setup) test because it assumes the overall list is invariant:
var index;
for (index = 0; index < toFind.length; ++index) {
if (!(toFind[index] in theDictionary)) {
throw "Error";
}
}
The Array#indexOf test (note that some very old implementations of JavaScript may not have Array#indexOf):
var values = theString.split(" ");
var index;
for (index = 0; index < toFind.length; ++index) {
if (values.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The Array#indexOf (ignore setup) test, which like Dictionary (ignore setup) assumes the overall list is invariant:
var index;
for (index = 0; index < toFind.length; ++index) {
if (theArray.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
Instead of looking for the fastest solution, you first need to make sure that you’re actually having a correct solution. Because there are four cases an e-mail address can appear and a naive search can fail:
Alone: user#example.com
At the begin: user#example.com ...
At the end: ... user#example.com
In between: ... user#example.com ...
Now let’s analyze each variant:
To allow arbitrary input, you will need to escape the input properly. You can use the following method to do so:
RegExp.quote = function(str) {
return str.toString().replace(/(?=[.?*+^$[\]\\(){}-])/g, "\\");
};
To match all four cases, you can use the following pattern:
/(?:^|\ )user#example\.com(?![^\ ])/
Thus:
var inList = new RegExp("(?:^| )" + RegExp.quote(needle) + "(?![^ ])").test(haystack);
Using indexOf is a little more complex as you need to check the boundaries manually:
var pos = haystack.indexOf(needle);
if (pos != -1 && (pos != 0 && haystack.charAt(pos-1) !== " " || haystack.length < (pos+needle.length) && haystack.charAt(pos+needle.length) !== " ")) {
pos = -1;
}
var inList = pos != -1;
This one is rather quite simple:
var dict = {};
haystack.match(/[^\ ]+/g).map(function(match) { dict[match] = true; });
var inList = dict.hasOwnProperty(haystack);
Now to test what variant is the fastest, you can do that at jsPerf.
indexOf() is most probably the fastest just keep in mind you need to search for two possible cases:
var existingEmails = "email1, email2, ...";
var newEmail = "somethingHere#email.com";
var exists = (existingEmails.indexOf(newEmail + " ") >= 0) || (existingEmails.indexOf(" " + newEmail ) > 0);
You're asking a question with too many unstated variables for us to answer. For example, how many times do you expect to perform this search? only once? A hundred times? Is this a fixed list of emails, or does it change every time? Are you loading the emails with the page, or by AJAX?
IF you are performing more than one search, or the emails are loaded with the page, then you are probably best off creating a dictionary of the names, and using the Javascript in operator.
If you get the string from some off-page source, and you only search it once, then indexOf may well be better.
In all cases, if you really care about the speed, you're best off making a test.
But then I'd ask "Why do you care about the speed?" This is a web page, where loading the page happens at network speeds; the search happens at more or less local-processor speed. It's very unlikely that this one search will make a perceptible difference in the behavior of the page.
Here is a little explanation:
Performing a dictionary lookup is relatively complicated - very fast compared with (say) a linear lookup by key when there are lots of keys, but much more complicated than a straight array lookup. It has to calculate the hash of the key, then work out which bucket that should be in, possibly deal with duplicate hashes (or duplicate buckets) and then check for equality.
As always, choose the right data structure for the job - and if you really can get away with just indexing into an array (or List) then yes, that will be blindingly fast.
The above has been taken from one of the blog posts of #Jon Skeet.
I know this is an old question, but here goes an answer for those who might need in the future.
I made some tests and the indexOf() method is impossibly fast!
Tested the case on Opera 12.16 and it took 216µs to search and possibly find something.
Here is the code used:
console.time('a');
var a=((Math.random()*1e8)>>0).toString(16);
for(var i=0;i<1000;++i)a=a+' '+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16);
console.timeEnd('a');
console.time('b');
var b=(' '+a).indexOf(((Math.random()*1e8)>>0).toString(16));
console.timeEnd('b');
console.log([a,b]);
In the console you will see a huge output.
The timer 'a' counts the time taken to make the "garbage", and the timer 'b' is the time to search for the string.
Just adding 2 spaces, one before and one after, on the email list and adding 1 space before and after the email, you are set to go.
I use it to search for a class in an element without jQuery and it works pretty fast and fine.

How do I perform a Javascript match with a pattern that depends on a variable?

The current implementation of Remy Sharp's jQuery tag suggestion plugin only checks for matches at the beginning of a tag. For example, typing "Photoshop" will not return a tag named "Adobe Photoshop".
By default, the search is case-sensitive. I have slightly modified it to trim excess spaces and ignore case:
for (i = 0; i < tagsToSearch.length; i++) {
if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) === 0) {
matches.push(tagsToSearch[i]);
}
}
What I have tried to do is modify this again to be able to return "Adobe Photoshop" when the user types in "Photoshop". I have tried using match, but I can't seem to get it to work when a variable is present in the pattern:
for (i = 0; i < tagsToSearch.length; i++) {
var ctag = jQuery.trim(currentTag.tag);
if (tagsToSearch[i].match("/" + ctag + "/i")) { // this never matches, presumably because of the variable 'ctag'
matches.push(tagsToSearch[i]);
}
}
What is the correct syntax to perform a regex search in this manner?
If you want to do regex dynamically in JavaScript, you have to use the RegExp object. I believe your code would look like this (haven't tested, not sure, but right general idea):
for (i = 0; i < tagsToSearch.length; i++) {
var ctag = jQuery.trim(currentTag.tag);
var regex = new RegExp(ctag, "i")
if (tagsToSearch[i].match(regex)) {
matches.push(tagsToSearch[i]);
}
}
Instead of
"/" + ctag + "/i"
Use
new RegExp(ctag, "i")
You could also continue to use indexOf, just change your === 0 to >= 0:
for (i = 0; i < tagsToSearch.length; i++) {
if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) >= 0) {
matches.push(tagsToSearch[i]);
}
}
But then again, I may be wrong.

Categories