recognize element content and modify dynamically using jquery - javascript

I'm injecting text into page using jquery like this
$("#myDiv").text(someWebServiceResponse.Data);
this returned data is in most cases numbers divided with commas but in some cases can be
string as a title which is followed with numbers
Returned data case without title
1,2,3,4,89,11
Returned data case with title
MyTitle 1,2,3,4,89,11
Returned data case with title
MyTitle2 1,2,35,4,89,14
Those title and number values are dynamic ofcourse.
How can I recognize if returned data contains title (maybe using typeofstring) and
modify this returned string with title + and than numbers in next line

Given that the numbers are divided only by , and not by space, you can easily test if the string contains empty space.
Like this
function containsTitle(input) {
return input.indexOf(' ') > 0;
}
...
if (containsTitle(someWebServiceResponse.Data)) {
//TODO: split for 2 lines or whatever you need
}

With your quoted examples, just find the last space if any and insert the plus sign:
var lastSpace = yourString.lastIndexOf(' ');
if (lastSpace != -1) {
yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
}
Live Example:
test("1,2,3,4,89,11");
test("MyTitle 1,2,3,4,89,11");
test("MyTitle2 1,2,35,4,89,14");
function test(yourString) {
var lastSpace = yourString.lastIndexOf(' ');
if (lastSpace != -1) {
yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
}
snippet.log(yourString);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

try this:-
var isTitle=function(txt){
var first=txt.substr(0,txt.indexOf(','));
return !$.isNumeric(first);
}
//here how to use
alert(isTitle('1,2,3,4,89,11'));
alert(isTitle('MyTitle 1,2,3,4,89,11'));
Demo

Related

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

Setting nested loop value returns error "e.replace is not a function"

I am trying to parse poems so that each line is an item in the tileset array, and each word is an item within that array (2 levels). I want each word to be in a span, and (later) each new line to have a break between.
I run into problems when I loop through to change the value of individual word (tileset[a][b]) to be wrapped in a span.
Here is the code:
function tilify (){
var tiletext = $(".tile-set").html().trim().replace("<br>"," ").replace(/ +(?= )/g," "); // trimming whitespace and regulating newline format to a double-space
tileset = tiletext.split(" "); // creating an array of lines
for (a in tileset) {
tileset[a] = tileset[a].split(" "); // creating a nested array of words
for (b in tileset[a]) {
tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span>"; // returns error
};
};
$(".tile-set").html(tileset);
}
tilify();
The error returned is Uncaught TypeError: e.replace is not a function
I have tried several loop syntaxes. I've also tried getting rid of the .replace method that I use just in case. It works if I wrap elements of the first array in the span tags, but not the second.
I have jquery and jqueryUI running.
Again this is the block I'm having trouble with:
for (b in tileset[a]) {
tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span>"; // returns error
};
Here is the body of the HTML
<div class='container'>
<p class='tile-set'>
The boot is famous to the earth,
more famous than the dress shoe,
which is famous only to floors.
</p>
</div>
Your code is breaking on the $(".tile-set").html(tileset); line because the $.html() can't handle a nested array. It's looking for an array of strings. If you want to include everything in one element, you'll need another for loop and then concat the whole thing like this:
for(a in tileset) {
$(".tile-set").html($(".tile-set").html()+tileset[a]);
}
Does something like this do what you want?
function tilify (){
var tiletext = $(".tile-set").html().trim().replace("<br>"," ").replace(/ +(?= )/g," "); // trimming whitespace and regulating newline format to a double-space
tileset = tiletext.split(" "); // creating an array of lines
$(".tile-set").html(""); // Set the html to be an empty string so we can concatenate
for (a in tileset) {
tileset[a] = tileset[a].split(" "); // creating a nested array of words
for (b in tileset[a]) {
$(".tile-set").html( $(".tile-set").html() + "<span class='tile'>" + tileset[a][b] + "</span>" );
};
};
}
tilify();
}
You get this output Thebootisfamoustotheearth, morefamousthanthedressshoe, whichisfamousonlytofloors but you can modify the <span></span> tags to work the way you want it.
The problem was trying to pass a nested array into the .html() method (thanks Phil). I passed the text into a tilesetBody variable and used that instead.
function tilify () {
var tiletext = $(".tile-set").html().trim().replace("<br>"," ").replace(/ +(?= )/g," ").replace(/,/g, "").replace(/\./g,"").replace(/\;/g,"");
var tilesetBody = "";
tileset = tiletext.split(" ");
for (a in tileset) {
tileset[a] = tileset[a].split(" ");
for (b in tileset[a]) {
if (tileset[a][b] != "") {
tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span> ";
tilesetBody += tileset[a][b];
}
};
tilesetBody += "<br>";
};
$(".tile-set").html(tilesetBody);
}

JavaScript: Can someone tell me what's going wrong with my code?

I've been doing JavaScript exercises since i haven't been doing this for too long. Got most of them working but i've been staring blind at this one.
I need to make all lowercase upper & vice versa. I checked the solution and it was helpfull but i'm sure i can get my own code ( which is very different from the answer ) working as well.
Thanks for all bits of help.
function swapCase (str) {
var sen = str;
for ( var i = 0; i < sen.length; i++) {
if (sen.charAt(i) === sen.charAt(i).toLowerCase()) {
sen.charAt(i).toUpperCase();
} else if (sen.charAt(i) === sen.charAt(i).toUpperCase()) {
sen.charAt(i).toLowerCase();
}
} return sen;
}
console.log(swapCase("UPlowUPlow"));
P.s: I am aware that it's not the cleanest bit of code but i've been working on it for a while. :)
toUpperCase and toLowerCase return the modified string, they don't modify it in place. So you'd have to put that value into the string you're processing, e.g.:
sen = sen.substring(0, i - 1) + sen.charAt(i).toUpperCase() + sen.substring(i + 1);
As that's fairly awkward, you'd probably be better off converting the string into an array of single-character strings, processing the array, then combining it again.
You can convert a string into an array of single character strings like this:
theArray = theString.split("");
...then process each entry, in a loop or via Array#map:
theArray[i] = theArray[i].toUpperCase();
...and then convert it back when done:
theString = theArray.join("");
Here's an example using Array#map:
function swapCase (str) {
var theArray = str.split("");
theArray = theArray.map(function(ch) {
var lower = ch.toLowerCase();
return ch === lower ? ch.toUpperCase() : lower;
});
return theArray.join("");
}
var str = "UPlowUPlow";
snippet.log("Before: " + str);
str = swapCase(str);
snippet.log("After: " + str);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Here's the concise version:
function swapCase (str) {
return str.split("").map(function(ch) {
var lower = ch.toLowerCase();
return ch === lower ? ch.toUpperCase() : lower;
}).join("");
}
var str = "UPlowUPlow";
snippet.log("Before: " + str);
str = swapCase(str);
snippet.log("After: " + str);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
sen.charAt(i).toUpperCase() does not change the character at the position. You need to manually update it.
function swapCase (str) {
var sen = str;
var updatedStr = "";
for ( var i = 0; i < sen.length; i++) {
if (sen.charAt(i) === sen.charAt(i).toLowerCase()) {
updatedStr += sen.charAt(i).toUpperCase();
} else if (sen.charAt(i) === sen.charAt(i).toUpperCase()) {
updatedStr += sen.charAt(i).toLowerCase();
}
}
return updatedStr;
}
As a side note, remember that strings are immutable, quoting:
In JavaScript, strings are immutable objects, which means that the
characters within them may not be changed and that any operations on
strings actually create new strings. Strings are assigned by
reference, not by value. In general, when an object is assigned by
reference, a change made to the object through one reference will be
visible through all other references to the object. Because strings
cannot be changed, however, you can have multiple references to a
string object and not worry that the string value will change without
your knowing it
Thanks for the great answers, people!
Thanks to you guys, i "solved" this in seconds while i was working on it for a good amount of time.
I'd love to upvote your answers instead of writing a thank you note, but i'm not yet allowed to do that. So, i'll do it this way.

Javascript substring check

I am working with images, they all have their sizes mentioned in their name tag.
http://mysite.com/audio/display%20image/130x130%20jpeg/5755285.jpg
I am getting those is an array of strings. I need to check if the string contains the size
130x130 in it. How can it be done?
var str = 'http://mysite.com/audio/display%20image/130x130%20jpeg/5755285.jpg';
var search = '130x130';
str.indexOf(search);
If it returns anything but -1 the string has been found:
if (str.indexOf(search) > -1) {
// Your image contains 130x130
} else {
// Your image does not contains 130x130
}

Javascript say if a folder is child of another

I have these strings which are addresses of files and folder:
../../../folder1/sub1/sub12/
../../../folder1/
../../../another-folder/
I want to compare them using javascript - possibily jquery - to see if for example string 1 have a part egual to string 2 but something more saying that string 1 is child of string 2.
How can i do this?
you could try something like the following
var path1 = "../../../folder1/";
var path2 = "../../../folder1/sub1/sub12/";
if (path2.indexOf(path1) != -1){
//path2 is a sub of path 1
}
In case your string can contain also absolute paths or paths containing .. not only at the beginning I would recommend checking if .indexOf return 0 instead of anything that is not -1.
It can help with cases like.
var path1 = "/rootFolder/";
var path2 = "../folder/rootFolder/";
if (path2.indexOf(path1) === 0) {
console.log("You want this"); // won't get executed => good
}
if (path2.indexOf(path1) !=-1) {
console.log("You don't want this"); // will get executed => bad
}
if(string1.indexOf(string2) != -1){
//string2 is present in string1
}
else{
//string2 is not present in string1
}
You can use the indexOf method to find whether one string is a part of another string.
From w3schools documentation:
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
var test = "../folder/subfolder1";
var test2 = "../folder";
if (test.indexOf(test2) !=-1) {
alert(test + " is a subfolder of " + test2);
}

Categories