Find the next word after matching a word in Javascript - 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]);

Related

How to not Count Spaces in Search Box? [duplicate]

I'm new to this, so please understand me;/
I'm creating an app in appery.io and it has to count the number of letters of text inserted by the app user(without spaces).
I have an input field created(input), a button to press and show the result in a label(result)
the code for the button:
var myString = getElementById("input");
var length = myString.length;
Apperyio('result').text(length);
Can you please tell me what is wrong?
To ignore a literal space, you can use regex with a space:
// get the string
let myString = getElementById("input").value;
// use / /g to remove all spaces from the string
let remText = myString.replace(/ /g, "");
// get the length of the string after removal
let length = remText.length;
To ignore all white space(new lines, spaces, tabs) use the \s quantifier:
// get the string
let myString = getElementById("input").value;
// use the \s quantifier to remove all white space
let remText = myString.replace(/\s/g, "")
// get the length of the string after removal
let length = remText.length;
Use this:
var myString = getElementById("input").value;
var withoutSpace = myString.replace(/ /g,"");
var length = withoutSpace.length;
count = 0;
const textLenght = 'ABC ABC';
for (var i = 0, len = textLenght.length; i < len; i++) {
if (textLenght[i] !== ' ')
count++;
}
You can count white spaces and subtract it from lenght of string for example
var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount);
console.log('total count:- ', my_string.length - spaceCount)

Separate characters and numbers from a string

I have a string variable that contain character and numbers like this
var sampleString = "aaa1211"
Note that variable always start with a character/s and end with number/s. Character and number size is not fixed. It could be something like followings
var sampleString = "aaaaa12111"
var sampleString = "aaa12111"
I need to separate the characters and numbers and assign them into separate variables.
How could I do that ?
I try to use split and substring but for this scenario I couldn't apply those. I know this is a basic question but i'm search over the internet and I was unable to find an answer.
Thank you
Please use
[A-Za-z] - all letters (uppercase and lowercase)
[0-9] - all numbers
function myFunction() {
var str = "aaaaAZE12121212";
var patt1 = /[0-9]/g;
var patt2 = /[a-zA-Z]/g;
var letters = str.match(patt2);
var digits = str.match(patt1);
document.getElementById("alphabets").innerHTML = letters;
document.getElementById("numbers").innerHTML = digits;
}
Codepen-http://codepen.io/nagasai/pen/pbbGOB
A shorter solution if the string always starts with letters and ends with numbers as you say:
var str = 'aaaaa12111';
var chars = str.slice(0, str.search(/\d/));
var numbs = str.replace(chars, '');
console.log(chars, numbs);
You can use it in a single regex,
var st = 'red123';
var regex = new RegExp('([0-9]+)|([a-zA-Z]+)','g');
var splittedArray = st.match(regex);
var num= splittedArray[0];
var text = splittedArray[1];
this will give you both the text and number.
Using Match
const str = "ASDF1234";
const [word, digits] = str.match(/\D+|\d+/g);
console.log(word); // "ASDF"
console.log(digits); // "1234"
The above will work even if your string starts with digits.
Using Split
with Positive lookbehind (?<=) and Positive lookahead (?=):
const str = "ASDF1234";
const [word, digits] = str.split(/(?<=\D)(?=\d)/);
console.log(word); // "ASDF"
console.log(digits); // "1234"
where \D stands for not a digit and \d for digit.
Use isNaN() to differentiate
var sampleString = "aaa1211"
var newnum =""
var newstr =""
for(var i=0;i<sampleString.length;i++){
if(isNaN(sampleString[i])){
newstr = newstr+sampleString[i]
}else{
newnum= newstr+sampleString[i]
}
}
console.log(newnum) //1121
console.log(newstr) //aaa
If you're like me, you were looking to separate alphabets and numbers, no matter what their position is, Try this:
var separateTextAndNum = (x) => {
var textArray = x.split('')
var text = []
var num = []
textArray.forEach(t=>{
if (t>-1) {
num.push(t)
} else {
text.push(t)
}
})
return [text, num]
}
For ex - if you try this:
separateTextAndNum('abcd1234ava') // result [["a","b","c","d","a","v","a"],["1","2","3","4"]]
This isn't beautiful but it works.
function splitLettersAndNumbers(string) {
var numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var numbers, letters, splitIndex;
for (var i = 0; i < string.length; i++) {
if (numbers.indexOf(string[i]) > -1) {
letters = string.substring(0, i);
numbers = string.substring(i);
return [letters, numbers];
}
}
// in the chance that you don't find any numbers just return the initial string or array of the string of letters
return [string];
}
Essentially just looping through the string until you find a number and you split it at that index. Returning a tuple with your letters and numbers. So when you run it you can do something like this:
var results = splitLettersAndNumbers(string);
var letters = results[0];
var numbers = results[1];
A functional approach...
var sampleString = "aaaaa12111";
var seperate = sampleString.split('').reduce(function(start , item){
Number(item) ? start[0] += item : start[1] += item;
return start
},['',''])
console.log(seperate) //["12111", "aaaaa"]
You can loop through the string length, check it & add to the variable.
It is not clear if you want to assign each of the character to a variable or all alphabets to one variable & integers to another.
var sampleString = "aaa12111"
var _num = "";
var _alp = "";
for (var i = 0; i < sampleString.length; i++) {
if (isNaN(sampleString[i])) {
_num += sampleString[i];
} else {
_alp += sampleString[i];
}
}
console.log(_num, _alp)

How to reverse a string using loops in js

So I created this code and i was wondering how I would be able to loop depending on the amount of spaces there are in the userInput.
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
The main Objective of this program is to reverse the userInput by not using js methods
Input:
"Hello world"
Output:
world Hello
1) Split the string on ' ', save to an array of strings
2) Reverse the array
3) Join the array elements with ' '
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
var reversed = "";
while (length) {
reversed += test[--length];
}
Edit:
Woha! I should have been more careful using test.length instead of input length.
I will leave it for you as an practice to find and fix the bug I made.

Get characters before last space in string

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.

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