Unsure Of How To New-Line Each String Inside An Array - javascript

This was for my assignment, which I've handed in and already been graded on and passed. I guess this step wasn't necessary but in the sample my professor had it so I assumed we had to do it as well.
The problem was simple. Prompt the user to enter 5 student names, and then use an array to list the names in alphabetical order.
In the sample, they had the sorted student names on each new line. So:
Abby
Emma
Hannah
Jake
Zeek
<!DOCTYPE html>
<html>
<body>
<h2> Assignment 1 - Task 4: 5 Student List </h2>
<p id="task 4"></p>
<script>
var Student1 = prompt("Enter the student's name");
document.write(" Student 1: " + Student1);
document.write("<br>");
var Student2 = prompt("Enter the student's name");
document.write(" Student 2: " + Student2);
document.write("<br>");
var Student3 = prompt("Enter the student's name");
document.write(" Student 3: " + Student3);
document.write("<br>");
var Student4 = prompt("Enter the student's name");
document.write(" Student 4: " + Student4);
document.write("<br>");
var Student5 = prompt("Enter the student's name");
document.write(" Student 5: " + Student5);
document.write("<br>");
document.write("<br>");
document.write( "The sorted list:" );
var studentList = ["\n" + Student1, "\n" + Student2, "\n" + Student3, "\n" + Student4, "\n" + Student5];
document.write("<br>");
studentList.sort();
document.write(studentList);
</script>
</body>
</html>
I've tried:
var studentList = [Student1, \n, Student2, \n, Student3, \n, Student4, \n, Student5];
var studentList = [Student1, "\n", Student2, "\n", Student3, "\n", Student4, "\n", Student5];
var studentList = [Student1\n, Student2\n, Student3\n, Student4\n, Student5];
var studentList = [Student1, \n, Student2, \n, Student3, \n, Student4, \n, Student5];
I've also tried:
document.write(\n + studentList);
document.write("\n" + studentList);
The new line is \n from the sources I looked at, I also tried which also didn't work. All the solutions I looked at did not work and any variation of \n I tried either was wrong or broke the prompt. This is the very first assignment in the course so we haven't really covered anything else at all other than if/else and very very basic arrays.

HTML doesn't render newlines. Notice that this markup has newlines but the rendered output doesn't:
student 1
student 2
student 3
student 4
student 5
There are a number of ways to get HTML to render line breaks. The simplest is the <br/> element.
Appending a <br/> to the end of each line gets us the desired breaks:
student 1<br/>
student 2<br/>
student 3<br/>
student 4<br/>
student 5<br/>
To accomplish this with your array you could join the names with a <br/>:
const names = [
'student 1',
'student 2',
'student 3',
'student 4',
'student 5'
]
const withBreaks = names.join('<br/>');
// withBreaks is "student 1<br/>student 2<br/>student 3<br/>student 4<br/>student 5"
document.write(withBreaks);

Related

Javascript: Put the words from array between html tags

Suppose I have a string as below:
"Hello, world! I am posting a question on StackOverflow".
I also have a list of words that I want to make bold in an HTML-like text as below:
["Hello", "posting", "StackOverflow"]
I want to get the result as follows:
"<b>Hello<b/>, world! I am <b>posting<b/> a question on <b>StackOverflow<b/>."
Bonus:
It would be great to achieve this with a reliable library.
Make the word matching case-insensitive.
Support overlapping word matches.
You can try the following way:
let str = "Hello, world! I am posting a question on StackOverflow";
let strBoldArr = ["Hello", "posting", "StackOverflow"];
//split the string and iterate through each word
let strArr = str.split(/[ ]/).map((a) => {
//check if word exists in the other array
if(strBoldArr.some(i => a.startsWith(i))){
//check for character at the end
if(a.endsWith(",")){
//modify the string
a = "<b>" + a.slice(0,-1) + "</b>, ";
}
else{
//modify the string
a = "<b>" + a + "</b>";
}
}
return a;
}).join(" ");
console.log(strArr);
//test
document.write(strArr);

How to use Regex to capitalize a street address?

In my application, you can submit a street address, and in the front end I convert it all to lowercase to be stored in the database. Now when I fetch the data I get an address that looks like:
"1 pleasant valley drive"
Can I make a regex to capitalize the first letter of each word in the string?
End goal:
"1 Pleasant Valley Dr"
I'm currently using:
let addrFormat =
address?.split(" ")[0] +" " +
address?.split(" ")[1].charAt(0).toUpperCase() +
address?.split(" ")[1].substring(1) +
" " + address?.split(" ")[2].charAt(0).toUpperCase() +
address?.split(" ")[2].substring(1);
but I need it to scale. lets say the street address is:
1234 Rocky Mountain Road
Then I have a problem with my code because it wont capitalize the last word.
You can simply uppercase the letters that aren't proceeded by a word character.
This can be checked with a word-boundary \b
let address = "1 pleasant valley drive";
address = address.replace(/\b(\w)/g, (m,g) => g.toUpperCase())
console.log(address);

How to remove all the white spaces between two words?

I have an input field on which the user types the city name, but what if the user types the city like this:
"New York "
" New York "
I used the trim function but that did not work, any suggestion?
const city = "New York ";
console.log(city.trim());
How can I remove all the white spaces so I can save the city in the state as "New York"?
You can also use replace to replace all consecutive space characters with one space:
const str = "New York "
" New York "
const res = str.replace(/\s+/gm, " ").trim()
console.log(res)
Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:
const str = "New York "
" New York "
const res = str.split(" ").filter(e=>e).join(" ")
console.log(res)
Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method
const city = " New York ";
console.log(city.replace(/\s+/g, ' ').trim());

jQuery Replace Second Space of Sentence

I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.

Javascript - catch name in variable string

I'm trying to catch a person's name. The name would be entered in a text box such as:
my name is Robert or yes my name is Robert etc.
I don't know where the actual name will fall however because of intro words etc.
I was thinking something like this.
I search for "my name is"
I capture it in an array
I split the array
I now know the actual name follows as such:
namesParts[0] - would be "my"
namesParts[1] - would be "name"
namesParts[2] - would be "is"
namesParts[3] - would be the name i'm looking for.
Something perhaps like the below but this doesn't work.
if (input.search("my name is")!= -1) {
var names = input.match(/my name is/);
var namesParts = names.split(' ');
var one = namesParts[3];
document.result.result.value = "Ok your name is "+one+".";
return true;
}
If all other words will start with lower case letter you could use
'my name is Robert'.match(/[A-Z]+\w*/);
otherwise
'My name is Robert'.match(/my name is (\S+)/i);
Check the JavaScript String.split Method.
Examples:
var str="my name is Robert";
var n=str.split('my name is ');
alert('1. Length: '+n.length +' Array: '+ n);
var str="my name is Robert";
var n=str.split(' ');
alert('2. Length: '+n.length +' Array: '+ n);
var str="my name is Robert";
var n=str.split('');
alert('3. Length: '+n.length +' Array: '+ n);
Live example: http://jsfiddle.net/a4D8q/

Categories

Resources