charAt first letter of last word in a string - javascript

I am trying to select the first letter of the last word in a string: such as the first letter after the last space.
"Hello World"
I need to select "W"
"Hello World I am young"
need to select "y"
using charAt()
thanks

You can split string by empty space, pop last element and ask for it's first letter:
"Hello World".split(" ").pop().charAt(0); // W

Using lastIndexOf function:
var str = "Hello World";
str.charAt(str.lastIndexOf(' ') + 1)

A string is just an array of characters, so you can access it with square brackets. In order to get the first letter of each word in your string, try this:
var myString = "Hello World"
var myWords = myString.split(" ");
myWords.forEach(function(word) {
console.log(word[0]);
});
For just the last word in a string:
var myString = "Hello World"
var myWords = myString.split(" ");
console.log(myWords[myWords.length-1][0]);

If you are just allowed to use charAt do the following:
Iterate through the whole string and always remember the last position you have found an empty space. If you are at the end of the string take the char next to the position you have remembered for the last empty space you have found.
Be aware of the case that your string ends with an empty space. If this could be the case you will probably need two indexes. Also take care if your string does not contain any empty space.

Related

How to check whether a string with more words contains a substring with more words in JavaScript?

This answer helps a lot when we have one word in string and one word in substring. Method includes() do the job. Any idea how to solve this if there is more than one word in string and more then one word in substring? For example:
const string = "hello world";
const substring = "hel wo";
console.log(string.includes(substring)); --> //This is false, but I want to change the code to return true
Should I create some arrays from string and substring using split(" ") and than somehow compare two arrays?
You can split the "substring" on whitespace to get an array of all substrings you want to look for and then use Array.prototype.every() to see if all substrings are found:
const string = "hello world";
const substring = "hel wo";
console.log(substring.split(/\s+/).every(substr => string.includes(substr)));
you can use regex for this:
var str = "hello world";
var patt = new RegExp(/.{0,}((?:hel)).{0,}((?:wo)).{0,}/ig);
console.log(patt.test(str));

splitting string is returning full string

I want to create a small script which determines how many words are in a paragraph and then divides the paragraph depending on a certain length. My approach was to split the paragraph using split(), find out how many elements are in the array and then output some of the elements into one paragraph and the rest into another.
var para = document.getElementById('aboutParagraph').innerHTML;
var paraElements = para.split();
var paraLength = paraElements.length;
if(paraLength >= 500){
}
console.log(paraElements);
when I use this code paraElements is being returned in an array where the first element is the entire string.
Sof for example if the paragraph were "this is a paragraph" paraElements is being returned as: ["this is a paragraph"], with a a length of 1. Shouldn't it be ["this", "is", "a", "paragraph"]?
var str = "this is a paragraph";
var ans = str.split(' ');
console.log(ans);
You need to use split(' ') with this format. Use ' ', notice space there. You were not passing any parameter by which to split.
The split() method splits a string at a delimiter you specify (can be a literal string, a reference to a string or a regular expression) and then returns an array of all the parts. If you want just one part, you must pass the resulting array an index.
You are not supplying a delimiter to split on, so you are getting the entire string back.
var s = "This is my test string";
var result = s.split(/\s+/); // Split everywhere there is one or more spaces
console.log(result); // The entire resulting array
console.log("There are " + result.length + " words in the string.");
console.log("The first word is: " + result[0]); // Just the first word
You are missing the split delimiter for a space. Try this:
var para = document.getElementById('aboutParagraph').innerHTML;
var paraElements = para.split(' ');
var paraLength = paraElements.length;
if(paraLength >= 500){
}
console.log(paraElements);
The split() will return an array, if you don't pass in a delimiter as an argument it would encapsulate the whole string into one element of an array.
You can break your words on spaces, but you may want to also consider tabs and newlines. For that reason, you could use some regex /\s+/ which will match on any whitespace character.
The + is used so that it treats all consecutive whitespace characters as one delimiter. Otherwise a string with two spaces, like foo bar would be treated as three words with one being an empty string ["foo", "", "bar"] (the plus makes it ["foo", "bar"] as expected).
var para = document.getElementById('aboutParagraph').innerHTML;
var paraElements = para.split(/\s+/); // <-- need to pass in delimiter to split on
var paraLength = paraElements.length;
if (paraLength >= 500) {}
console.log(paraLength, paraElements);
<p id="aboutParagraph">I want to create a small script which determines how many words are in a paragraph and then divides the paragraph depending on a certain length. My approach was to split the paragraph using split(), find out how many elements are in the array and then output some of the elements into one paragraph and the rest into another.</p>

How can I get a substring located between 2 quotes?

I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!
Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.
http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
​alert(matches[1]);​
If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

How to remove the last word in a string using JavaScript

How can I remove the last word in the string using JavaScript?
For example, the string is "I want to remove the last word."
After using removal, the string in the textbox will display "I want to remove the last"
I've seen how to remove the last character using the substring function, but because the last word can be different every time. Is there a way to count how many words are required to remove in JavaScript?
Use:
var str = "I want to remove the last word.";
var lastIndex = str.lastIndexOf(" ");
str = str.substring(0, lastIndex);
Get the last space and then get the substring.
An easy way to do that would be to use JavaScript's lastIndexOf() and substr() methods:
var myString = "I want to remove the last word";
myString = myString.substring(0, myString.lastIndexOf(" "));
You can do a simple regular expression like so:
"I want to remove the last word.".replace(/\w+[.!?]?$/, '')
>>> "I want to remove the last"
Finding the last index for " " is probably faster though. This is just less code.
Following answer by Amir Raminfar, I found this solution. In my opinion, it's better than accepted answer, because it works even if you have a space at the end of the string or with languages (like French) that have spaces between last word and punctuation mark.
"Je veux supprimer le dernier mot !".replace(/[\W]*\S+[\W]*$/, '')
"Je veux supprimer le dernier"
It strips also the space(s) and punctuation marks before the last word, as the OP implicitly required.
Peace.
Fooling around just for fun, this is a funny and outrageous way to do it!
"I want to remove the last word.".split(" ").reverse().slice(1).reverse().join(" ")
Use the split function:
var myString = "I want to remove the last word";
var mySplitResult = myString.split(" ");
var lastWord = mySplitResult[mySplitResult.length-1]
The shortest answer to this question would be as below,
var str="I want to remove the last word".split(' ');
var lastword=str.pop();
console.log(str.join(' '));
You can match the last word following a space that has no word characters following it.
word=/s+\W*([a-zA-Z']+)\W*$/.exec(string);
if(word) alert(word[1])
If anyone else here is trying to split a string name in to last name and first name, please make sure to handle the case in which the name has only word.
let recipientName = _.get(response, 'shipping_address.recipient_name');
let lastWordIndex = recipientName.lastIndexOf(" ");
let firstName = (lastWordIndex == -1) ? recipientName : recipientName.substring(0, lastWordIndex);
let lastName = (lastWordIndex == -1) ? '' : recipientName.substring(lastWordIndex + 1);
To get the last word
const animals = "I want to remove the last word.".split(" ");
console.log(animals.slice(-1));
Expected output: word.
To remove the last word
console.log(animals.slice(0, -1).join(" ");
Expected output: "I want to remove the last"

Reversing a string

I want to reverse a string, then I want to reverse each word in it. I was able to reverse the string. But couldn't reverse words in it.
Given Str = "how are you"
Expected Result = "you are how"
My code
var my_str="how are you";
alert(my_str.split('').reverse().join(''));
Result I get: uoy era woh
How to get the final result??
the other answers are entirely correct if your string has only 1 space between words.
if you have multiple spaces between words, then things are a bit different:
to get just the words, in reverse order, rejoined by 1 space:
str.split(/\s+/).reverse().join(" ")
to reverse the entire string, and still have the original whitespace:
str.split(/\b/).reverse().join('')
the first one uses a regex, "/\s+/", to match an entire run of spaces, instead of a single space. it rejoins the words with a single space.
the second one uses a regex, "/\b/", to just split on the boundaries between words and non-words. since the runs of spaces will be preserved, it just rejoins with an empty string.
I think you've got an empty string in there: my_str.split('')
Make sure you put a space: my_str.split(' ')
The problem is you are splitting with the empty string instead of the space character. Try this:
var str = "how are you";
alert(str.split(" ").reverse().join(" "));
Try it here.
If you are using ES6 then you could use this -
let myStr="How are you";
console.log([...myStr].reverse().join(''));

Categories