I'm wondering how to console.log a word from a string based on the index.
let word = "Hello world";
console.log(word[0]) //log from index 0 to 4
How to log from index 0 to 4, because now i only know how to log a single letter.
Like this:
let word = "Hello world";
let wordArray = word.split(" ");
console.log(wordArray[0])
Split your string by your separator in your case space:
console.log(word.split(" ")[0]);
You can either use split to get an array of the words and then use to index of the word position
let sentence = "Hello world";
console.log(sentence.split(" ")[0]);
or if you know what word you are looking for you
can use indexOf together with the word length to slice it.
let sentence = "Hello world";
console.log(sentence.slice(sentence.indexOf("Hello"), "Hello".length));
Its ez mate,
first create function
function clwobo(str){
let a = str.split(" ")//Create an "a" variable to split "str" into an array
return a[0]//This function will return the first word of the string, 1 will be 2 and so on
}
How to use this function?
Well
clwobo("Hello world")
In console it will show
-- Console --
Hello
Try it first, then mark if its work.
Related
I have a string like this
term = "Hey there how you doing?"
Now because of some issues in the API, I sometimes receive undefined in the beginning of the string.
term = "#0undefinedHey there how you doing?"
OR
term = "#1undefined Hey there how you doing?"
Now I can check the presence of undefined in the beginning of the sentence by doing something like
if(term.indexOf("undefined") == 0) {
//processing logic
}
But as you can see there is a presence of #n with the undefined where n can be any single digit number.
I want a regex solution such that it ignores #n and looks for undefined in the beginning of the sentence and remove the #n and undefined.
So the final string if undefined is present will be
term = "Hey there how you doing?" // removed #nundefined
How can I do this with regex?
let s = "#0undefined Hello World!";
console.log(s.replace(/^\#[0-9]*undefined\s*/,''));
const regex = RegExp('^\#[0-9]*undefined');
console.log('Has undefined = ' + regex.test(s));
If this number next to undefined makes any sense to you, you can try:
const matches = "#1undefined Hey there how you doing?".match(/#([0-9]*)undefined ?(.*)/);
console.log(matches);
This will give you the number under matches[1] while your cleaned message will be at matches[2].
If you just care about the message, you can use .replace as another user suggested to clean your output:
const output = "#1undefinedHey there how you doing?".replace(/#([0-9]*)undefined ?/, '');
console.log(output);
Hi sorry for the simple question but how can I detect the last two words in the String?
Let say I have this var:
var sample = "Hello World my first website";
How can I get the last two words dynamical. I tried the split().pop but only the last word is getting
var testing = sample.split(" ").pop();
console.log(testing)
Just try with:
var testing = sample.split(" ").splice(-2);
-2 takes two elements from the end of the given array.
Note that splice again give an array and to access the strings again the you need to use the index which is same as accessing directly from splitted array. Which is simply
var words =sample.split(" ");
var lastStr = words[words.length -1];
var lastButStr = words[words.length -2];
If you prefer the way you are doing. you are almost there. Pop() it again.
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
var sample = "Hello World my first website";
var words= sample.split(" ");
var lastStr = words.pop(); // removed the last.
var lastButStr= words.pop();
console.log(lastStr,lastButStr);
Note , pop() removes the element. And make sure you have enough words.
Or do it with a regex if you want it as a single string
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/[^ ]* [^ ]*$/g);
console.log(res);
var splitted = "Hello World my first website".split(" ");
var testing = splitted.splice(splitted.length - 2);
console.log(testing[0] + " " + testing[1]);
try this one
var sample = "Hello World my first website";
var testing = sample.split(" ").slice(-2);
console.log(testing)
You could also try something like:
sample.match(/\w+\W+\w+$/);
Try this.
var testing = sample.split(" ").splice(-2).join(' ');
First we have to split the string using split function,then by using splice we can get last two words and concatenate those two words by using join function.
please check this
sample.split(" ").splice(-2).join(" ");
The problem can be solved in several ways. the one I prefer is the following that splits the problem in sub problem:
transoform a sentence in an array
get last 2 items of an array
Transform a sentence in an array
let sentence = "Server Total Memory Capacity is: 16502288 MB";
let sentenceAsArray = sentence.split(' ');
Get last items of an array
let numberOfItems = 2;
let lastTwo = sentenceAsArray.splice(-numberOfItems)
Join array items
At the beginning we transformed a sentence into an array. Now we have to do the complementary operation: transform an array into a sentece.
let merged = lastTwo.join(' ')
Print into console
Now that we have new variable with desired content, can show it printing variable into the console with the following command.
console.log(merged)
You can use substr function
var sample = "Hello World my first website";
var testing = sample.substr(sample.length -2);
how do i reverse a sentence like "Hello World" to "World Hello" Not dlroW oleo
Been search for an example on this forum the whole day
function jump(str){
var holder ="";
var len = str.length-1;
for(var i =len; i >= 0; i--){
holder += str[i] ;
}
return holder.trim();
}
console.log(jump("Just do it!"))
In JavaScript there is a really easy way to do this:
var str = "Hello World";
str = str.split(" ").reverse().join(" ");
console.log(str); // => "World Hello"
Basically, you split the string into an array using a space character as a delimiter so we can get an array of each word, then reverse that array and join them back into a string with the spaces we removed earlier.
As you have not mentioned which language you are using, I will give you just steps
Steps:
Split by space, and store in an array or list
Reverse the order
Print by looping through the list
I m using a local JavaScript executed on Chrome browser.
I really don't understand why this is providing the wrong result:
Script:
var str = "hello 1 test test hello 2";
var patt = /(hello \S+)/g;
var res = str.split(patt);
//var res = str.search(patt);
if(res!=null) {
for(var i=0;i<res.length;i++) console.log(i+res[i]);
}
Output:
0
1hello 1
2 test test
3hello 2
4
Expected Result:
0hello 1
1hello 2
What am I doing wrong?!
Looks like you're looking for matches rather than splitting the string
Use str.match(patt)
str.match
Instead, your answer is splitting the string twice, as your regular expression matches in two places. Splitting a string by regex gives 3 parts. Before the match, the match, and after the match.
Your string has matched twice. Meaning that this process has happened twice, resulting in 5 parts, the result shown (two parts are empty).
split ... splits the string.
Just as splitting x,y,z by /(,)/ will give you ["x", ",", "y", ",", "z"], you get the result seen here.
What you wanted to do was iterate over the matches:
str.match(/(hello \S+)/g)
Match approach
With match, it is much simpler, just use /hello\s+\S+/g:
var str = "hello 1 test test hello 2";
var patt = /hello\s+\S+/g;
var res = str.match(patt);
if(res!=null) {
for(var i=0;i<res.length;i++)
console.log(i+res[i]);
}
Note that you do not need any capturing groups in this case as you are not using the captured text, you need the whole matched text. Besides, \s+ will match any whitespace there can be between hello and a sequence of non-whitespace characters.
Split approach
You need to match the rest of the string that is after hello \S+ and remove blank entries before outputting them:
var str = "hello 1 test test hello 2";
var patt = /(hello \S+).*?(?=$|hello \S)/g;
var res = str.split(patt);
//var res = str.search(patt);
if(res!=null) {
res = res.filter(Boolean);
for(var i=0;i<res.length;i++)
if (res[i]) {
console.log(i+res[i]);
}
}
Result:
0hello 1
js:21 1hello 2
The regex - (hello \S+).*?(?=$|hello \S) - matches and captures the hello + a sequence of non-whitespace symbols, and then any characters but a newline up to the end of string or next hello + non-whitespace characters.
I have used res.filter(Boolean); to remove empty elements in the resulting array (that almost always are present when splitting with regex).
You used split, then you have an array with all values before and after each match of /(hello \S+)/g.
You want to use match:
"hello 1 test test hello 2".match(/(hello \S+)/g);
// ["hello 1", "hello 2"]
Is there a way to determine the number of times a letter occurs inside another string?
if not, can you determine the number of times a string is in an array
if you can do it with the array, how can you split 2 words, such as: Hello, World! into an array of 2 words, like this:
["Hello", "World"]
Sure. A simple one liner that comes to mind is
var numOccurrences = str.split("<char>").length -1
where can be replaced with whatever character (or string) you want to test for
That will split the string on each occurrence and then take the length of the resulting array -1. Which will tell you the number of occurrences.
If you want to do it while ignoring upper/lower case, you can use regex
str.match(/<char>/gi).length
The number of times a letter occurs in a string
This can be found as follows:
"Hello World Hello World!".match(/e/g).length // Will result in 2
/e/g is a regular expression that matches the letter 'e'. The 'g' stands for "global" and gets all the occurances in a string.
String in an array
This can be found as follows:
var arrayOfStrings = ["Hello", "World", "Hello", "World"],
wordCount = 0,
i;
for (i = 0; i < arrayOfStrings.length; i += 1) { // Remember to optimise length call
if (arrayOfStrings[i] === "Hello") {
wordCount += 1;
}
}
console.log(wordCount) // This will log 2