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.
Related
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);
I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']
I am brand new at programming, especially JS. I seem to be stuck on a split string.
I need to split a string into two separate strings. I know I can do so with the slice and substr like below, which is my sample I have of what I know. I am assuming my name is Paul Johnson. with below I know that if I have an output of first and last name with the parameters I setup, I will have Paul as my first name and Johnson as my second.
var str = document.getElementById("fullName").value;
var firstname = str.slice(0, 4);
var lastname = str.substr(4, 13);
My question is that I am getting hung up on how to find the space and splitting it from there in order to have a clean cut and the same for the end.
Are there any good resources that clearly define how I can do that?
Thanks!
What you're after is String split. It will let you split on spaces.
http://www.w3schools.com/jsref/jsref_split.asp
var str = "John Smith";
var res = str.split(" ");
Will return an Array with ['John','Smith']
str.indexOf(' ') will return the first space
There is a string split() method in Javascript, and you can split on the space in any two-word name like so:
var splitName = str.split(" ");
var firstName = splitName[0];
var lastName = splitName[1];
http://www.w3schools.com/jsref/jsref_split.asp
A good way to parse strings that are space separated is as follows:
pieces = string.split(' ')
Pieces will then contain an array of all the different strings. Check out the following example:
string_to_parse = 'this,is,a,comma,separated,list';
strings = string_to_parse.split(',');
alert(strings[3]); // makes an alert box containing the string "comma"
Use str.split().
The syntax of split is: string.split(separator,limit)
split() returns a list of strings.
The split() function defaults to splitting by whitespace with to limit.
Example:
var str = "Your Name";
var pieces = str.split();
var firstName = pieces[0];
var lastName = pieces[1];
pieces will be equal to ['Your', 'Name'].
firstName will be equal to 'Your'.
lastName will be equal to 'Name'.
I figured it out:
var str = document.getElementById("fullName").value;
var space = str.indexOf(" ");
var firstname = str.slice(0, space);
var lastname = str.substr(space);
Thank you all!
I want to exclude characters from displaying in a vbulletin template.
For example, if a user writes:
"[Hello World] How are you?"
I want to ecxlude "[" and "]" all that's inside so it only displays:
"How are you?"
Is there a way to do this?
Use JavaScript string operations .getIndexOf() and .substring(). Get the position of the first bracket, get the position of the second bracket, split the string into 3 substrings, the middle section being between the two indexed values, and then add just the first and third substrings together. Like this:
var string = "[Hello World] How are you?";
var bracket1 = string.getIndexOf("[");
var bracket2 = string.getIndexOf("]");
var substring1 = string.substring(0,bracket1);
var substring2 = string.substring(bracket1,bracket2);
var substring3 = string.substring(bracket2,string.length);
var solution = substring 1 + " " + substring 3;
At least, that's the concept. Everything may not be right on, but you could futz with the numbers a little to get it perfect.
Or if you don't need to worry about what comes before [], simply use .split():
var string = "[Hello World] How are you?";
var solutionArray = string.split("]");
var solution = solutionArray[1];
Hope this helps!
I want to use regular expression in javascript to extract values. The string is in this pattern "title{position}", how should i get title and position in this example?
Assuming that's all there is too it (no nesting of '{}'s or anything) (\w+)\{(\w+)\} will match that instance and group the results as groups 1 and 2. Do you need anything more complicated like a collection of many of these per string or is that enough?
Is that string everything? If so there's no need for matching. Just split the string!
var str = "foo{bar}";
var pieces = str.split(/\{|\}/);
var title = pieces[0];
var position = pieces[1];
alert("Title: " + title + "\nPosition: " + position);
Demonstrated here
If you did want to add results to a structure -
var arr = [];
var text = 'title{position}';
text.replace(/(\w+){(\w+)}/g, function(m, key, value){
//alert('title is-'+key);
//alert('position is-'+value);
arr.push({"title":key,"position":value});
});
console.log(arr);
Demo - http://jsfiddle.net/Sr6Ed/1/