How can I simplify below code? How can I get rid of the if statements? I want to highlight some lines in ajax response. Right now I have two strings to compare = two ifs. This number will increase so I am thinking of doing this some other way - using an array of the strings that needs to be highlighted in case the string is part of data_array element.
I prefer a solution in javascript only but jQuery is ok too.
data_array=data.split('<BR>');
for(var i=0, len=data_array.length; i < len; i++){
if (data_array[i].indexOf('Conflict discovered') >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
if (data_array[i].indexOf('Syntax error') >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
}
data=data_array.join('<BR>');
Add more elements to the array as desired :)
data.replace( /<br>/ig, '\n' ).replace(
new RegExp( '^(.*(?:' + [
'Conflict discovered'
, 'Syntax error'
].join( '|' ) + ').*)$', 'gm' )
, '<span class="red">$1</span>' ).replace( /\n/g, '<br>' );
explanation:
replace <br> tags with line breaks
make a regexp: ^(.*(?:Conflict discovered|Syntax error).*)$
surround matches with <span class="red"> ... </span>
turn line breaks back in to <br> tags
Why not add another for loop?
data_array=data.split('<BR>');
var stringsToFind = ['Conflict discovered', 'Syntax error'];
for (var i = 0; i < data_array.length; i++) {
for (var j = 0; j < stringsToFind.length; j++) {
var currItem = data_array[i];
if (currItem.indexOf(stringsToFind[j]) >= 0) {
data_array[i]='<span class="red">' + currItem + '</span>';
}
}
}
data = data_array.join('<BR>');
jQuery (note, may be slower, and I haven't tested this yet)
data_array=data.split('<BR>');
var stringsToFind = ['Conflict discovered', 'Syntax error'];
$.each(data_array, function(i, item) {
$.each(stringsToFind, function(j, s) {
if (item.indexOf(s) >= 0) {
data_array[i]='<span class="red">' + item + '</span>';
}
}
});
data = data_array.join('<BR>');
var data_array = data.split('<BR>');
var errMsgs = ['Conflict discovered', 'Syntax error'];
data_array = data_array.map(function(data_rec) {
var isAnError = errMsgs.some(function (errMsg) {
return data_rec.indexOf(errMsg) >= 0;
});
if (isAnError) {
return "<span class='red'>" + data_rec + '</span>';
} else {
return data_rec;
}
});
jsBin demo
var highlightWords = ['Conflict discovered', 'Syntax error', 'Simply cool'];
for(i=0; i<highlightWords.length; i++){
var regex = new RegExp(highlightWords[i],'ig');
data= data.replace( regex, '<span class="red">'+ highlightWords[i] +'</span>');
}
$('div').html( data );
jsBin demo 2 all line highlight
var words = ['Conflict discovered', 'Syntax error', 'Strange'];
var data_array=data.split('<BR>');
for(n=0;n<words.length;n++){
for(i=0; i<data_array.length; i++){
if (data_array[i].indexOf( words[n] ) >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
}
data = data_array.join('<BR>');
}
$('div').html( data );
data_array=data.split('<BR>');
for(var i=0, len=data_array.length; i < len; i++){
var dai = data_array[i];
if (dai.indexOf('Conflict discovered') >= 0 || dai.indexOf('Syntax error') >= 0){
data_array[i] = "<span class='red'>"+dai+"</span>";
}
}
data=data_array.join('<BR>');
Related
I am trying to decode my string using JavaScript. Here is my code on JSBin.
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length -2 &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
console.log(i +"i")
console.log(str);
}
console.log("after");
console.log(str);
}
I make a function in which message and key is passed.
Expected output :: open
Actually string charters are repeated in input message (encrypted message) using key. So I need to decode the message.
You forgot to put a break in the else condition, that's why it was looping infinitely till it ran out of memory. Run it in a browser and the tab will crash:
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
else
break;
}
console.log("after");
console.log(str); // prints open
}
By the way, a better way to write the loop would be:
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str = '';
var j = 0, i = 0;
while (j < keysplit.length
&& i < msg.length) {
str += msg[i];
i += parseInt(keysplit[j]);
j++;
}
console.log(str)
}
This may helps you.
decordMessage('oppeeennnn', '1234');
function decordMessage(m, k) {
var arr = m.split("");
uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
console.log(uniqueArray.join(""));
}
Assuming encryption logic goes as 123456....
Sample here
I am trying to replace ` ticks with html code in a string.
var str = "this `code` and `here`"
my expected output
"this code and here"
What i am trying to do is below
.
get the positions with ticks in a string
replace those ticks with span html based on odd and even occurence.
not sure, i couldnt get expected and my browser gets hang. and
when i debug it. i see there is no index for string to replace.
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
You can use String.prototype.replace() with RegExp
/(`\w+`)/g
String.prototype.slice() with parameters 1, -1 to slice string within backtick
`
characters
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
.code {
background: turquoise;
}
scope of var i is wider then you think, so pos.push(i) will have them all same at the end
replaceAt appends incorrect ending
replaceAt shifts rest of the string invalidating positions you found
I believe you wanted something along these lines:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)
Use the JavaScript replace method.
var str = "this `code` and `here`";
var newStr = str.replace("`", "");
I have searched too much on same topic but not is perfect for what I am looking for.
I have a string like :
var string ='<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>'
Now what I want is to substring it with limit with javascript substring function but don't want tags to be cut in middle like for example
<strong><span>Hii </span> <p
It should be like
<strong><span>Hii </span> <p>
I am using
string.substr(0,200)
string is dynamic variable with html tags
My solution:
function smart_substr(str, len) {
var temp = str.substr(0, len);
if(temp.lastIndexOf('<') > temp.lastIndexOf('>')) {
temp = str.substr(0, 1 + str.indexOf('>', temp.lastIndexOf('<')));
}
return temp;
}
http://jsfiddle.net/8t6fs67n/
Its not elegant but it works, will increase the characters to include the next closing tag
https://jsfiddle.net/q680vors/
Just change length to the required number of characters.
var string ='<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>';
var length = 2;
var openTag = 0, closeTag = 0,i=0;
for(i; i<length; i++)
{
if(string[i] == "<")
openTag++;
if(string[i] == ">")
closeTag++;
}
if(openTag > closeTag)
{
while(string[i] != ">")
i++;
}
var newString = string.substring(0,(i+1));
alert(newString);
I don't see reason to do so, but theoretically something like this:
function substrWithTags(str, len) {
var result = str.substr(0, len),
lastOpening = result.lastIndexOf('<'),
lastClosing = result.lastIndexOf('>');
if (lastOpening !== -1 && (lastClosing === -1 || lastClosing < lastOpening)) {
result += str.substring(len, str.indexOf('>', len) + 1);
}
return result;
}
var s = '<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>'
// <strong><span>Hii </span> <p>this is just a demo <spa
s.substr(0, 53);
// <strong><span>Hii </span> <p>this is just a demo <span>
substrWithTags(s, 53);
I think my function is more accurate when it comes to being more sensitive on the content syntax. If your substring length cuts a word in half for example, the word will be included fully.
function HTML_substring(string, length) {
var noHTML = string.replace(/<[^>]*>?/gm, ' ').replace(/\s+/g, ' ');
var subStringNoHTML = noHTML.substr(0, noHTML.indexOf(" ", length));
var words = subStringNoHTML.split(" ");
var outPutString = "";
var wordIndexes = [];
words.forEach((word, key) => {
if (key == 0) {
outPutString += string.substr(0, string.indexOf(word) + word.length);
wordIndexes[key] = string.indexOf(word) + word.length;
} else {
let i = wordIndexes[key - 1];
outPutString += string.substring(i, string.indexOf(word, i) + word.length);
wordIndexes[key] = string.indexOf(word, i) + word.length;
}
});
return outPutString;
}
If I understood you correctly, you want to to do something like this?
var limit = 28;
var test = '';
var string = '<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>';
do {
test = string.substring(0,limit);
limit++;
} while(test.charAt(test.length-1) !== '>');
test will be equal to '<strong><span>Hii </span> <p>'
or will ends with any another closing tag which is above your limit
Well, I did a function:
function my_substring (str) {
var answer = [], x;
for (var i=0, l=str.length; i<l; i++) {
x = i;
if (str[i] == '<') {
while (str[++i] != '>');
answer.push( str.substring(x, i+1) );
}
else {
while (++i < l && str[i] != '<');
answer.push( str.substring(x, i) );
i--;
}
}
return answer;
}
var string =
"<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>"
console.log ( my_substring(string) );
This code will output:
["<strong>",
"<span>",
"Hii ",
"</span>",
" ",
"<p>",
"this is just a demo ",
"<span>",
"string",
"<span>",
"</p>",
"</strong>"
]
Then you can select what you want in the array. Hope it helps.
I have this in a Div (Text actually "wraps" because Div box has short width; except where line breaks are intentional):
"Now is the time
for all good men
to come to the aid
of their country"
"The quick brown fox
jumps over the
lazy dogs"
I would like this:
lazy dogs"
jumps over the
"The quick brown fox"
of their country"
to come to the aid
for all good men
"Now is the time
I've tried using Reverse(); but am not getting the desired results.
Note: I'm not trying to reverse a string per say, but actual lines of text (ie: sentences).
If you got line breaks like this \n, you can do the following:
var lineBreak = "\n",
text = "Now is the time\nfor all good men\nto come to the aid\nof their country";
text = text.split(lineBreak).reverse().join(lineBreak);
If the line break is another sign, change the variable lineBreak.
OK, got it eventually. Based on this answer of mine, I came up with a code that identifies the actual lines inside textarea, even when wrapped.
Next step was to translate div into textarea so we can use the above trick.
Having this, it's simple matter of manipulating the lines using .reverse() method.
Final code is:
$("#btnInvert").click(function() {
var placeholder = $("#MyPlaceholder");
if (!placeholder.length) {
alert("placeholder div doesn't exist");
return false;
}
var oTextarea = $("<textarea></textarea>").attr("class", placeholder.attr("class")).html(placeholder.text());
oTextarea.width(placeholder.width());
//important to assign same font to have same wrapping
oTextarea.css("font-family", placeholder.css("font-family"));
oTextarea.css("font-size", placeholder.css("font-size"));
oTextarea.css("padding", placeholder.css("padding"));
$("body").append(oTextarea);
//make sure we have no vertical scroll:
var rawTextarea = oTextarea[0];
rawTextarea.style.height = (rawTextarea.scrollHeight + 100) + "px";
var lines = GetActualLines(rawTextarea);
var paragraphs = GetParagraphs(lines).reverse();
lines = [];
for (var i = 0; i < paragraphs.length; i++) {
var reversedLines = paragraphs[i].reverse();
for (var j = 0; j < reversedLines.length; j++)
lines.push(reversedLines[j]);
if (i < (paragraphs.length - 1))
lines.push("");
}
rawTextarea.value = lines.join("\n");
placeholder.html(rawTextarea.value.replace(new RegExp("\\n", "g"), "<br />"));
oTextarea.remove();
});
function GetParagraphs(lines) {
var paragraphs = [];
var buffer = [];
$.each(lines, function(index, item) {
var curText = $.trim(item);
if (curText.length === 0) {
if (buffer.length > 0) {
paragraphs.push(buffer);
buffer = [];
}
} else {
buffer.push(curText);
}
});
if (buffer.length > 0)
paragraphs.push(buffer);
return paragraphs;
}
function GetActualLines(oTextarea) {
oTextarea.setAttribute("wrap", "off");
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
return oTextarea.value.split("\n");
}
Just put the actual ID of your div and it should work.
Live test case.
warning, this is pseudo code :
lines=[];
index=0;
start=0;
for(characters in alltext){
if(newLine){
lines.push(alltext.substring(start,index);
start=index;
}
i++
}
sortedLines=[]
for(var i=lines.length;i>-1;i--){
sortedLines.push(lines[i]);
html=$('selector').html();
html+=lines[i];
$('selector').append(html);
}
better use split
I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is
function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");
//Loop through those items
for (var i = 0; i < list.length; ++i) {
//Reset all class names to description
list[i].className = "description";
}
if (e.className == "description"){
//Set the css class for the clicked element
e.className += " show";
}
else{
if (e.className == "description show"){
return;
}
}}
and I am using it on this page dev.msmnet.com/services/practice-management to show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.
I was curious to see what a jQuery version of your function would look like, so I came up with this:
function showDesc(name) {
var e = $("#" + name);
$(".description.show").removeClass("show");
if(e.attr("class") == "description") {
e.addClass("show");
} else if(e.hasClass("description") && e.hasClass("show")) {
return;
}
}
This should support multiple classes.
function getElementsByClassName(findClass, parent) {
parent = parent || document;
var elements = parent.getElementsByTagName('*');
var matching = [];
for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
matching.push(elements[i]);
}
}
return matching;
}
You can pass in a parent too, to make its searching the DOM a bit faster.
If you want getElementsByClassName('a c') to match HTML <div class="a b c" /> then try changing it like so...
var elementClasses = elements[i].className.split(/\s+/),
matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
found = 0;
for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {
if (matchClasses.indexOf(elementClasses[j]) > -1) {
found++;
}
}
if (found == matchClasses.length) {
// Push onto matching array
}
If you want this function to only be available if it doesn't already exist, wrap its definition with
if (typeof document.getElementsByClassName != 'function') { }
Even easier jQuery solution:
$('.service').click( function() {
var id = "#" + $(this).attr('id') + 'rt';
$('.description').not(id).hide();
$( id ).show();
}
Why bother with a show class if you are using jQuery?
Heres one I put together, reliable and possibly the fastest. Should work in any situation.
function $class(className) {
var children = document.getElementsByTagName('*') || document.all;
var i = children.length, e = [];
while (i--) {
var classNames = children[i].className.split(' ');
var j = classNames.length;
while (j--) {
if (classNames[j] == className) {
e.push(children[i]);
break;
}
}
}
return e;
}
I used to implement HTMLElement.getElementByClassName(), but at least Firefox and Chrome, only find the half of the elements when those elements are a lot, instead I use something like (actually it is a larger function):
getElmByClass(clm, parent){
// clm: Array of classes
if(typeof clm == "string"){ clm = [clm] }
var i, m = [], bcl, re, rm;
if (document.evaluate) { // Non MSIE browsers
v = "";
for(i=0; i < clm.length; i++){
v += "[contains(concat(' ', #"+clc+", ' '), ' " + base[i] + " ')]";
}
c = document.evaluate("./"+"/"+"*" + v, parent, null, 5, null);
while ((node = c.iterateNext())) {
m.push(node);
}
}else{ // MSIE which doesn't understand XPATH
v = elm.getElementsByTagName('*');
bcl = "";
for(i=0; i < clm.length; i++){
bcl += (i)? "|":"";
bcl += "\\b"+clm[i]+"\\b";
}
re = new RegExp(bcl, "gi");
for(i = 0; i < v.length; i++){
if(v.className){
rm = v[i].className.match(bcl);
if(rm && rm.length){ // sometimes .match returns an empty array so you cannot use just 'if(rm)'
m.push(v[i])
}
}
}
}
return m;
}
I think there would be a faster way to iterate without XPATH, because RegExp are slow (perhaps a function with .indexOf, it shuld be tested), but it is working well
You can replace getElementsByClassName() with the following:
function getbyclass(n){
var elements = document.getElementsByTagName("*");
var result = [];
for(z=0;z<elements.length;z++){
if(elements[z].getAttribute("class") == n){
result.push(elements[z]);
}
}
return result;
}
Then you can use it like this:
getbyclass("description") // Instead of document.getElementsByClassName("description")