I'm trying to take a string with blank spaces and display each word line-by-line in console output.
My javascript code takes a string and creates an array of indexes where spaces are identified using an indexOf() operation. This is then passed through a slice loop which subtracts the different indexes to get a length of the string to slice and the space index to locate it in the existing string. The output is the final console.log and it appears to do what I need it to even when passing in random strings.
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
console.log("string length = ", fourStr.length);
var i = 0;
var n = 0;
var sentence = [i];
for (n = 0; n < fourStr.length; n++) {
var pos = fourStr.indexOf(sp, n) //find the index of the space
if (n == pos) {
sentence[i] = pos; //place the index in an array
i++;
} else(i);
}
var arraysent = fourStr.split(sp); //test split function for string
console.log("Array Sentence:\n", arraysent)
console.log("space index length:\n", sentence.length) //check array length
console.log("space index array:\n", sentence) //display array with "space" indexes
console.log("sliced string:\n", fourStr.slice(sentence[0] - 1, sentence[0])); //display first index
var j = 0;
for (j = 0; j < sentence.length; j++) {
var slicesent = fourStr.slice(sentence[j], sentence[j + 1]); //automate remaining index display
console.log(slicesent);
}
I was hoping to find an easier/simpler way to do this same task since passing the string to the array is not efficient and re-creates the string a bunch of times. Could someone please explain a better alternative that will show the individual words of a string line-by-line in the console?
Thank you
This is literally done by String.split()
function logWordsBySpaces(str){
let arr = str.split(" ");
arr.forEach(function(a){ console.log(a); })
}
logWordsBySpaces("Karma karma karma karma karma chameleon!")
You should use .split
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
const result = [myStr, twoStr, stringadd, threeStr, fourStr].map(string => string.split(sp));
console.log(result);
Related
I have a nested loop that will work most of the time, but for one particular case it does not run at all.
Here is the value that is failing: 1, 3-5, 7-10, 22
JS code:
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = Range[0];
end = Range[Range.length-1];
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
When the failing value is entered, this is the result:
Range: 1
Result in loop: 1,
Range: 3,5
Result in loop: 1,3,
Result in loop: 1,3,4,
Result in loop: 1,3,4,5,
Range: 7,10 <--- Never goes inside the loop
Range: 22
Result in loop: 1,3,4,5,22,
Result: 1,3,4,5,22
I can't figure out why the 7-10 part is being skipped. Any help or explanation is greatly appreciated.
Here is the FIDDLE
You need use parseInt when work with integer here
start = parseInt(Range[0],10);
end = parseInt(Range[Range.length-1],10);
After splittng you get array with strings, and when you try compare "7" with "10" it compared as string and "7" always greater then "10", because char code for '7' greater than char code for '1' (first char in "10")
For converting to number you can use next function also: Number, parseInt or parseFloat
document.getElementById("myButton").addEventListener("click", function() {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = parseInt(Range[0], 10);
end = parseInt(Range[Range.length - 1], 10);
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
// Log is my imitation of console.log()
function Log(stuff) {
var msg = document.getElementById("msg");
var newDiv = document.createElement("div");
newDiv.innerHTML = stuff;
msg.appendChild(newDiv);
}
<p>Try this value in the input: 1, 3-5, 7-10, 22</p>
<input id="myIn" type="text" />
<button id="myButton" type="button">Go</button>
<p id="msg"></p>
Since you are using a text input field all values from that field are strings. Then you use string manipulations that return more string values. You are never dealing with numbers. So Javascript will treat them as string values when testing if one value is greater than the other.
You can use the Number global object to safely cast a string value to a number. The benefit of Number over parseInt and parseFloat is if any part of the string is non numeric it will return a NaN value whereas the other two will return as much of the string as a number up to the first non-numeric character.
start = Number(Range[0]);
//I'm trying to enter 4 words through a prompt and split them up and assign each word to a variable
var answer = prompt("Enter a sentence");
for(var i = 0; i < answer.length; i++){
if(answer[i] === " "){
var firstWord = answer.slice(0, answer.indexOf(" "));
var secondWord = answer.slice(answer.indexOf(" ") + 1, name.indexOf(" "));
var thirdWord = answer.slice();
var fourthWord = answer.slice();
}
}
You can take advantage of a string's .split() method.
solution:
var answer = prompt("Enter a sentence");
var words = answer.split(" ");
var firstWord = words[0];
var secondWord = words[1];
var thirdWord = words[2];
var fourthWord = words[3];
This is dependent on having your prompt separated with a single whitespace and you are only entering 4 words. .split() is a method that will look at the string that called it, and split up the string into an array, separated by the parameter value (in this case " ").
String.prototype.split() Documentation on MDN
I got this string:
var longText="This is a superuser test, super user is is super important!";
I want to know how many times the string "su" is in longText and the position of each "su".
I was trying with:
var nr4 = longText.replace("su", "").length;
And the difference of lenght between the main text and the nr4 divided by "su" lenght beeing 2 is resulting a number of repetitions but i bet there is a better way of doing it.
For example
var parts=longText.split("su");
alert(parts.length-1); // length will be two if there is one "su"
More details using exec
FIDDLE
var re =/su/g, pos=[];
while ((result = re.exec(longText)) !== null) {
pos.push(result.index);
}
if (pos.length>0) alert(pos.length+" found at "+pos.join(","));
Use exec. Example amended from the MDN code. len contains the number of times su appears.
var myRe = /su/g;
var str = "This is a superuser test, super user is is super important!";
var myArray, len = 0;
while ((myArray = myRe.exec(str)) !== null) {
len++;
var msg = "Found " + myArray[0] + ". ";
msg += "Next match starts at " + myRe.lastIndex;
console.log(msg, len);
}
// "Found su. Next match starts at 12" 1
// "Found su. Next match starts at 28" 2
// "Found su. Next match starts at 45" 3
DEMO
Could do :
var indexesOf = function(baseString, strToMatch){
var baseStr = new String(baseString);
var wordLen = strToMatch.length;
var listSu = [];
// Number of strToMatch occurences
var nb = baseStr.split(strToMatch).length - 1;
for (var i = 0, len = nb; i < len; i++){
var ioF = baseStr.indexOf(strToMatch);
baseStr = baseStr.slice(ioF + wordLen, baseStr.length);
if (i > 0){
ioF = ioF + listSu[i-1] + wordLen;
}
listSu.push(ioF);
}
return listSu;
}
indexesOf("This is a superuser test, super user is is super important!","su");
return [10, 26, 43]
var longText="This is a superuser test, super user is is super important!";
var count = 0;
while(longText.indexOf("su") != -1) { // NB the indexOf() method is case sensitive!
longText = longText.replace("su",""); //replace first occurence of 'su' with a void string
count++;
}
I am getting the number of carriage return in a string like so
var str = str.split(/\n/).length;
I would like to limit my string so that after 5 cr's the string removes only those carriage returns after the max allowed.
Can anyone lend a hand on the syntax for this.
Thank you, heres my attempt.
this flattens the entire string after 5, I would like to retain the first 5 then flatten then string
function countLineBreaks(str){
var n = str.split(/\n/).length;
return n;
};
var n = countLineBreaks(myStr);
if(n > 5)
str = str.replace(/\n/g, " ");// replace cr's with empty space after 5
You might be able to do it with regexes, but you can also just do it with splitting and joining:
var split = str.split("\n");
var first6 = split.splice(0, 6); // remove first 6 elements into first6
var result = first6.join("\n") + (split.length ? " " + split.join(" ") : "");
Split the array, merge all items after 5, and then join it back in.
function trimString(str) {
var lines = str.split(/\n/);
if(lines.length > 5) {
var rest = lines.slice(5);
lines.length = 5;
lines[5] = rest.join(' ');
}
return lines.join('\n');
}
friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});