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

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

Related

converting array pattern string to array and sort in javascript

I have a string includig array symbol and double quote
var abc = '["Free WiFi","Breakfast for 2","Accommodation"]'
now i want this to convert into array and then sort this array.
the final result i want is Accomodation, Breakfast for 2, Free WiFi.
if array conversion and sorting is not require then also its fine.
how can we do it?
Just use JSON.parse and .sort:
var abc = JSON.parse('["Free WiFi","Breakfast for 2","Accommodation"]').sort().join(', ')
console.log(abc);
Another option just for fun
var abc = '["Free WiFi","Breakfast for 2","Accommodation"]';
// With help of RegExp
match = (abc.replace(/(?:\[)*\"(.*?)\"(?:\])*/g, (m,g) => g)).split(",").sort().join(', ');
// Log
console.log(match)

Extract strings between occurences of a specific character

I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);

How to detect the last 2 words using 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);

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

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.

Categories

Resources