How to detect the last 2 words using Javascript? - javascript

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);

Related

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

Split text with a single code

var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];

Counting commas in a string with Javascript (AngularJS/Lodash)

I have a rather specific problem.
I'm using ng-csv, and because it doesn't support nested arrays, I'm turning an array into a string.
Something like this:
[
{"name":"Maria","chosen":false},
{"name":"Jenny","chosen":false},
{"name":"Ben","chosen":false},
{"name":"Morris","chosen":false}
]
Turns into:
$scope.var = "Maria, Jenny, Ben, Morris"
My problem is that when I was using the array I was able to count the number of names in the array (which I need for UI reasons), but with the string it gets tricky.
Basically, I cannot count the number of words because some names might include last name, but I thought I could count commas, and then add 1.
Any pointers on how to do just that?
If you need names itself - you may use method split of String class:
var str = "Maria, Jenny, Ben, Morris";
var arr = str.split(','); // ["Maria", " Jenny", " Ben", " Morris"]
var count = arr.length; // 4
var str = "Maria, Jenny, Ben, Morris";
var tokens = str.split(",");
The number of tokens should be captured in tokens.length. Alternately, if you don't actually need to work with the tokens directly:
var nameCount = str.split(",").length;
Why not use regex?
var _string = "Mary, Joe, George, Donald";
_string.match(/,/g).length // 3

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

Javascript: Time and Info splitting

From server I get data as such:
"07.00 PROGRAM DESCRIPTION"
"07.20 PROGRAM DESCRIPTION 2"
I want to split them into a 2 indexed array such as: ["07.00", "PROGRAM DESCRIPTION 2"]. Regular split( " " ) would not work me as the description part contains severaral " " spaces.
I will be grateful for any suggestion.
Regards
You could use:
var parts = str.split(' '),
time = parts.shift(),
description = parts.join(' ');
or, to get your array:
var parts = str.split(' ');
parts[1] = parts.slice(1).join(' ');
;)
You need somekind of a pattern, which is reliable. If it's always the case that you need to split just between the first whitespace character to you can do:
var blub = "07.00 PROGRAM DESCRIPTION",
pos = blub.indexOf(" "),
arr = [];
arr[0] = blub.slice(0, pos);
arr[1] = blub.slice(pos + 1);
or you might just want to use regular expression. Since I don't pretend to be a genius on that field here is my little suggestion:
var blub = "07.00 PROGRAM DESCRIPTION",
arr = /(\d+\.\d+)\s(.*)/.exec(blub);
var pattern = /([0-9]{2}\.[0-9]{2})\s(.+)/;
var data = "07.00 PROGRAM DESCRIPTION";
var parsed = pattern.exec(data);
console.log(parsed); // (Array) ["07.00 PROGRAM DESCRIPTION", "07.00", "PROGRAM DESCRIPTION"]
this is flexible and easier to adapt in case the format changes (just change the pattern and use that var anywhere else in your code)
The substring method:
var time = row.substring(0,4);
var description = row.substring(5);
Or, with the split method:
row = row.split(" ",1);
The second parameter is the maximum number of splits... so it'll only split at the first space. Edit: this won't work. Use the first method instead.

Categories

Resources