Get characters before last space in string - javascript

Is there a way to obtain all characters that are after the last space in a string?
Examples:
"I'm going out today".
I should get "today".
"Your message is too large".
I should get "large".

You can do
var sentence = "Your message is too large";
var lastWord = sentence.split(' ').pop()
Result : "large"
Or with a regular expression :
var lastWord = sentence.match(/\S*$/)[0]

try this:
var str="I'm going out today";
var s=str.split(' ');
var last_word=s[s.length-1];

var x = "Your message is too large";
function getLastWord(str){
return str.substr(str.lastIndexOf(" ") + 1);
}
alert(getLastWord(x)); // output: large
// passing direct string
getLastWord("Your message is too large"); // output: large

use string.lastIndexOf():
var text = "I'm going out today";
var lastIndex = text.lastIndexOf(" ");
var result = '';
if (lastIndex > -1) {
result = text.substr(lastIndex+1);
}
else {
result = text;
}
UPDATE: Comment edited to add check if there's no space in the string.

Related

How to split/divide a string of array into two groups with Javascript

I'm given an array of strings. Its a text with actions in brackets. Ex.
"John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him."
The end result I'd like would be
actionArray = " [waves]
speechArray = "John sees his neighbor and greets 'Hello!'. But she didn't hear him."
The actionArray would be spaced for each character so the action tag would be on top of the speechArray during the action. I've approached this problem using the following method.
var array = data.toString().split("\n");
for(i in array) {
var actionArray = "";
var speechArray = "";
for (var letter in array[i]){
if (array[i][letter] == "["){
actionArray += array[i][letter];
letter++;
while(array[i][letter] !== "]"){
actionArray += array[i][letter];
letter++;
}
if (array[i][letter] == "]"){
actionArray += array[i][letter];
}
}
if (array[i][letter] !== "["){
speechArray += array[i][letter];
actionArray += " ";
}
So to extract the part of the string with the action brackets, I have an if method that finds "[" and if it does, it would add it to the actionArray, keeps with the if and adding to actionArray until it finds the closing tag "]"
It works, but the counter letter doesn't continue where I left off after finding the closing tag, so the entire string still ends up being copied to the speechArray. And then I end up getting something like this
actionArray = " [waves]
speechArray = "John sees his neighbor and greets 'Hello!'.[waves] But she didn't hear him."
I'm new to Javascript, without the use of pointers I'm not sure how to approach this. Could someone point me tot he right direction? Thank you!
Just have a variable that tells you if you're "inside" an action and assign accordingly:
str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";
let action = '',
speech = '',
inAction = false;
for (let char of str) {
if (char === '[')
inAction = true;
if (inAction) {
action += char;
speech += ' ';
} else {
action += ' ';
speech += char;
}
if (char === ']')
inAction = false;
}
console.log(action)
console.log(speech)
And here's a more concise but far less readable solution with regexes:
str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";
let parts = ['', ''];
str.replace(/(\[.+?\])|[^\]\[]+/g, function (m, a) {
parts[a ? 1 : 0] += m;
parts[a ? 0 : 1] += ' '.repeat(m.length);
});
console.log(parts[1]);
console.log(parts[0]);
You can check this simple code snippet:
var data = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him."
var arr = data.split("");
var action = false;
var actionstr="",speachstr="";
for(var i=0;i<arr.length;i++){
if(arr[i]=='['){
action = true
}else if(arr[i] ==']'){
actionstr = actionstr.concat(arr[i])
speachstr = speachstr.concat(" ")
action = false
continue
}
if(action){
actionstr = actionstr.concat(arr[i])
speachstr = speachstr.concat(" ")
}else{
actionstr = actionstr.concat(" ")
speachstr = speachstr.concat(arr[i])
}
}
console.log(actionstr)
console.log(speachstr)
The output should be:
[waves]
John sees his neighbor and greets 'Hello!' . But she didn't hear him.
i have the below implementation,maybe it might be ok for you
var arr = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him."
var p = arr.split(/\s+/)
var c = p.map( value => {
if (/^\[.*\]/.test(value) )
return value;
else
return " "
})
var command = c.join(" ");
var strings = arr.replace(/\[.*\]/, " ".repeat(command.match(/\w+/)[0].length))
console.log(command)
console.log(strings)
A simple solution with regular expressions.
First the easy part (speechString):
var speechString = string.replace(/(\[[^\]]*\])/gi, (v)=>' '.repeat(v.length));
it just replaces [...] with the number of spaces equals to the length of the match.
Now the harder part (actionString):
var actionString = ((string)=>{
var ret = '';
var re = /(\[[^\]]*\])/gi;
var l = 0;
while((m = re.exec(string)) != null) {
ret += ' '.repeat(m.index-l) + string.substring(m.index, m.index+m[1].length);
l = m.index+m[1].length;
}
return ret;
})(string);
it defines the same regularexpression to find the [...], but uses the index (postion of the match) and the length of the match to build a string like expected.
Here is a working fiddle.
EDIT actionString can also retrieved by one single statement:
var actionString = string.replace(/([^\[]*)(\[[^\]]+?\])?/g, (v,p1,p2)=>{
return (p1?' '.repeat(p1.length):'')+(p2||'');
});
Match all characters and a [...] expression and replace it with spaces in the length of the first group length appended with the p2 match.
You can use String.prototype.match(), and String.prototype.replace() with RegExp /\[.+\]/ to match character beginning within "[" followed by one or more characters followed by and including "]", String.prototype.repeat()
let str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";
let re = /\[.+\]/;
let match = str.match(re);
let res = " ".repeat(match.index) + match[0]
+ " ".repeat(str.length - (match.index + match[0].length));
str = str.replace(re, " ".repeat(match[0].length));
let pre = document.querySelector("pre");
pre.textContent = res + "\n" + str;
<pre></pre>

Find the next word after matching a word in Javascript

Want to get the first word after the number from the string "Apply for 2 insurances".
var Number = 2;
var text = "Apply for 2 insurances or more";
In this case i want to get the string after the Number, So my expected result is "insurances"
A solution with findIndex that gets only the word after the number:
var number = 2;
var text = "Apply for 2 insurances or more";
var words = text.split(' ');
var numberIndex = words.findIndex((word) => word == number);
var nextWord = words[numberIndex + 1];
console.log(nextWord);
You can simply use Regular Expression to get the first word after a number, like so ...
var number = 2;
var text = "Apply for 2 insurances test";
var result = text.match(new RegExp(number + '\\s(\\w+)'))[1];
console.log(result);
var number = 2;
var sentence = "Apply for 2 insurances or more";
var othertext = sentence.substring(sentence.indexOf(number) + 1);
console.log(othertext.split(' ')[1]);
//With two split
console.log(sentence.split(number)[1].split(' ')[1]);

Remove all characters after the last special character javascript

I have the following string.
var string = "Welcome, to, this, site";
I would like to remove all characters after the last comma, so that the string becomes
var string = "Welcome, to, this";
How do I go about it in Javascript? I have tried,
var string = "Welcome, to, this, site";
string = s.substring(0, string.indexOf(','));
but this removes all characters after the first comma.
What you need is lastIndexOf:
string = s.substring(0, string.lastIndexOf('?'));
you can use split and splice to achieve the result as below.
var string = "Welcome, to, this, site";
string = string.split(',')
string.splice(-1) //Take out the last element of array
var output = string.join(',')
console.log(output) //"welcome, to, this"
There's a String.prototype.lastIndexOf(substring) method, you can just use that in replacement of String.prototype.indexOf(substring) :
var delimiter = ",";
if (inputString.includes(delimiter)) {
result = inputString.substring(0, inputString.lastIndexOf(delimiter));
} else {
result = inputString;
}
Alternatives would include Madara Uchiha's suggestion :
var delimiter = ",";
var parts = inputString.split(delimiter);
if(parts.length > 0) { parts.pop(); }
result = parts.join(delimiter);
Or the use of regular expressions :
result = inputString.replace(/,[^,]*$/, "");
Try this
var string = "Welcome, to, this, site";
var ss = string.split(",");
var newstr = "";
for(var i=0;i<ss.length-1;i++){
if (i == ss.length-2)
newstr += ss[i];
else
newstr += ss[i]+", ";
}
alert(newstr);

Get Full string using part of a given string

var string = "Let's say the user inputs hello world inputs inputs inputs";
My input to get the whole word is "put".
My expected word is "inputs"
Can anyone share your solution?
Thanks in advance
One way to do what you're asking is to split the input string into tokens, then check each one to see if it contains the desired substring. To eliminate duplicates, store the words in an object and only put a word into the result list if you're seeing it for the first time.
function findUniqueWordsWithSubstring(text, sub) {
var words = text.split(' '),
resultHash = {},
result = [];
for (var i = 0; i < words.length; ++i) {
var word = words[i];
if (word.indexOf(sub) == -1) {
continue;
}
if (resultHash[word] === undefined) {
resultHash[word] = true;
result.push(word);
}
}
return result;
}
var input = 'put some putty on the computer output',
words = findUniqueWordsWithSubstring(input, 'put');
alert(words.join(', '));
A RegEx and filter to remove duplicates;
var string = "I put putty on the computer. putty, PUT do I"
var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
item = item.toLowerCase();
return uniques[item] ? false : (uniques[item] = true);
});
document.write( result.join(", ") );
// put, putty, computer

Get first word of string

Okay, here is my code with details of what I have tried to do:
var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");
//Now I want to get the first word of every split-ed sting parts:
for (var i = 0; i < codelines.length; i++) {
//What to do here to get the first word of every spilt
}
So what should I do there? :\
What I want to get is :
firstword[0] will give "Hello"
firstword[1] will give "sss"
firstword[2] will give "mmm"
Use regular expression
var totalWords = "foo love bar very much.";
var firstWord = totalWords.replace(/ .*/,'');
$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Split again by a whitespace:
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var words = codelines[i].split(" ");
firstWords.push(words[0]);
}
Or use String.prototype.substr() (probably faster):
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var codeLine = codelines[i];
var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}
To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)
split(" ") will convert your string into an array of words (substrings resulted from the division of the string using space as divider) and then you can get the first word accessing the first array element with [0].
See more about the split method.
I 'm using this :
function getFirstWord(str) {
let spaceIndex = str.indexOf(' ');
return spaceIndex === -1 ? str : str.substring(0, spaceIndex);
};
How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
An improvement upon previous answers (working on multi-line or tabbed strings):
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
Or using search and substr:
String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}
Or without regex:
String.prototype.firstWord = function(){
let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
filter((e)=>e!==-1);
return sps.length? this.substr(0,Math.min(...sps)) : this;
}
Examples:
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab example 3'.firstWord()); // -> tab
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
var firstWord = str1[i].split(' ')[0];
alert(firstWord);
}
This code should get you the first word,
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :(
var words = str1[i].split(" ");
console.log(words[0]);
}
In modern JS, this is simplified, and you can write something like this:
const firstWords = str =>
str .split (/\|/) .map (s => s .split (/\s+/) [0])
const str = "Hello m|sss sss|mmm ss"
console .log (firstWords (str))
We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.
I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}
const getFirstWord = string => {
const firstWord = [];
for (let i = 0; i < string.length; i += 1) {
if (string[i] === ' ') break;
firstWord.push(string[i]);
}
return firstWord.join('');
};
console.log(getFirstWord('Hello World'));
or simplify it:
const getFirstWord = string => {
const words = string.split(' ');
return words[0];
};
console.log(getFirstWord('Hello World'));
This code should get you the first word,
const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));
Ans will be "Jahid"

Categories

Resources