Javascript separate string into different variables - javascript

I am looking to take a string and find all the spaces in it and separate that into different variables. I know I could use the .split() but that wouldn't make new variables. I would prefer to not use jQuery or other JavaScript library but if I have to, it wouldn't be the worst thing. Thanks!
Example, John M Peters would result in the variables fname: John, mname: M and lname:
Peters.

.split() just returns an array, so you can easily assign new variables using that...
var str = "John M Peters";
var fname = str.split(" ")[0];
var mname = str.split(" ")[1];
var lname = str.split(" ")[2];

You can split the string like so:
var name = 'John M Peters';
var arr = name.split(' ');
var obj = {fname: arr[0]};
if(arr.length === 1) {
obj.lname = arr[1];
} else {
obj.mname = arr[1];
obj.lname = arr[2];
}
console.log(obj.fname);
console.log(obj.mname); //could be undefined
console.log(obj.lname);
This solution will also work for a string that does not have a middle initial as well. You can see this example here: http://jsfiddle.net/nDwmY/2/

If you don't know how many spaces there are in the string, beforehand, you can do the following:
var str = "How are you doing today, my dear friend?";
numberspaces = str.split(" ").length; //you know how many spaces there are
words=str.split(" "); //it creates an array of words
var i;
for (i = 0; i < numberspaces; i++){
console.log(words[i]);}

I would create a function along these lines. This is just a quick-and-dirty and doesn't do any validation, I leave that up to you.
function parse_name(theName) {
var nameSplit = theName.split(" ");
var nameFields = {
first : nameSplit[0],
middle : nameSplit[1],
last : nameSplit[2]
};
return nameFields;
}
Then you can call it any time you need to parse a name.
var parsedName = parse_name("John M Smith");
alert(parsedName.first); // Should alert "John"
alert(parsedName.middle); // Should alert "M"
alert(parsedName.last); // Should alert "Smith"

In addition to the answers the others pointed out, I'd like to point out that Mozilla's JavaScript engine (spidermonkey) supports destructuring assignments:
<script language="javascript1.7">
var s = 'John M. Peters';
var fname, mname, lname;
[fname, mname, lname] = s.split(/\s+/);
alert('fname = ' + fname + ', mname = ' + mname + ', lname = ' + lname);
</script>
This is not portable, so not ideal for web programming. However, if you're writing a plugin for firefox or thunderbird or etc, then there are a number of interesting language extensions available.

Related

How can I dynamically use string.replace?

wordsArray = ['guy', 'like', 'sweet', 'potatoes']; //so on and so forth
string = "I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.";
DELIMITER = "**";
for (var i = 0; i < wordsArray.length; i++)
{
string.replace(DELIMITER, wordsArray[i]);
}
Hi, this is a simplified version of my code. I'm creating a mad lib, and the length of wordsArray will always be equal to the number of fill in the blanks. The problem with my current code is that in the for loop, it will replace every **. The thing is, I want to replace the entire thing, like **NOUN**, not just **. But since whatever is in between ** ** won't always be the same, string.replace() won't exactly work. Can Anyone suggest me an edit that could replace all the part of speeches but still eventually return string as a, well, block of proper text?
You can do it using string.match by catching all those **<STRINGS>** first:
var wordsArray = ['guy', 'like', 'sweet', 'potatoes'];
var string = "I am a **NOUN** and I **VERB-** **ADJECTIVE** **NOUN**.";
var DELIMITER = "**";
var newString = string; // copy the string
var stringArray = string.match(/(\*\*[A-Za-z-]+\*\*)/g); // array of all **<STRINGS>**
for (var i = 0; i < wordsArray.length; i++) {
newString = newString.replace(stringArray[i], wordsArray[i]);
}
console.log(newString);
You can bind your array to the replacer and call replace on your string once, I think it is much simpler:
"I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.".replace(/(\*\*\w+\*\*)/gi,(function(){
this._currentIndex = this._currentIndex || 0;
return this[this._currentIndex++];
}).bind(['guy', 'like', 'sweet', 'potatoes']));
//"I am a guy and I like sweet potatoes."
Using reduce:
const string = "I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.";
const newString = ['guy', 'like', 'sweet', 'potatoes'].reduce(
(theString, replacement) => theString.replace(/\*{2}\w+\*{2}/, replacement),
string
)

javascript - Break search query string into object

I am trying to build api query in client side by breaking the user input in search field into object.
Example,
Search query
arg1:"2 words" business corporate arg2:val2
Desired value
{
arg1: "2 words",
arg2: "val2",
extra: "business corporate"
}
I tried doing this.
var query = initquery.split(' ');
var obj = {};
for(var i=0; i<query.length; i++){
var s = query[i].split(':');
if(s.length == 2) {
initquery = initquery.replace(query[i], '');
obj[s[0]] = s[1];
}
}
obj.extra = initquery;
This does not handle string in quotes.
You may want to take a look at this:
addEventListener('load', function(){
var wtf = 'arg1:"2 words" business corporate arg2:val2 arg3:"fixedIt"';
function customObj(string){
var a = string.split(/\s+(?!\w+")/), x = [], o = {};
for(var i=0,s,k,l=a.length; i<l; i++){
s = a[i].split(/:/); k = s[0];
s[1] ? o[k] = s[1].replace(/"/g, '') : x.push(k);
}
o['extra'] = x.join(' ');
return o;
}
console.log(customObj(wtf));
});
Thanks to #Barmar for this helpful comment, I came up with this regex to catch the args (assuming they are followed by a single digit number and a colon):
var pattern = /((^|\s)arg\d:").*?(?=")"?|(\sarg\d:\w*)/g;
Extracting the rest of the query can be done through:
query.replace(pattern,"");
And then creating the final object should be straightforward. Still, given the complexities that could rise from sprinkling double quotes in the query string, you should consider writing a parser for your application.
UPDATE:
Updated the regex to match beginning of the string and only match arg after white space character.

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

logic to split this in javascript?

I have the following text,
Name:Jon
Age:25
Gender:Male
how to split this to get the following result,
Jon
25
Male
if i use this,
var results = file.split(":");
i get results[0]=Name, results[1]=JonAge, results[2]=25Gender,
and when i give,
var results = file.split("\n");
i get results[0]=Name:Jon, results[1]=Age:25,...
but i couldn't get the above, how to check for either a colon or a new line at the same time ?
You need to split first on the newline, then the colon:
file.split('\n').map(function(line){return line.split(':')[1];})
This could be accomplished with a loop, obviously, but the map function makes it nice and neat.
You could also use a regular expression:
file.match(/[^:]+$/gm)
Finally, you can extend the functionality of arrays by creating a split function that works on arrays:
Array.prototype.split = function(s) {
return this.map( function(x) { return.x.split(s); } );
}
Then you can chain your splits and you'll get an array of arrays:
var results = file.split('\n').split(':');
console.log( 'Name: ' + results[0][1] );
console.log( 'Age: ' + results[1][1] );
console.log( 'Gender: ' + results[2][1] );
Your choice of method depends a lot on how "safe" you want to be. I.e., are you concerned about malformed input or colons in the field names or values....
You can't. Use a for loop.
var r = file.split("\n");
var results = [];
for (var i = 0; i < r.length; i++) {
results[i] = r[i].split(":")[1];
}
This can be accomplished with two steps, first you'll want to split the text by newline:
lines = str.split( '\n' )
Then iterate over each line and split each one by a colon:
final = {};
for ( pair in lines ){
var split = lines[ pair ].split( ':' );
var name = split[ 0 ].trim(); //cleaning out any whitespacve
var value = split[ 1 ].trim(); //cleaning out any whitespacve
final[ name ] = value;
}
final is now:
Object {Name: "Jon", Age: "25", Gender: "Male"}

Splitting string from the first occurrence of a character

I have multiple lines of text in log files in this kind of format:
topic, this is the message part, with, occasional commas.
How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?
I've tried using this kind of split, but it doesn't work when there's more commas in the message part.
[topic, message] = whole_message.split(",", 2);
Use a regex that gets "everything but the first comma". So:
whole_message.match(/([^,]*),(.*)/)
[1] will be the topic, [2] will be the message.
That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:
var split = whole_message.split(',', 2);
var topic = split[0], message = split[1];
edit — ok so "split()" is kind-of broken; try this:
var topic, message;
whole_message.replace(/^([^,]*)(?:,(.*))?$/, function(_, t, m) {
topic = t; message = m;
});
Here!
String.prototype.mySplit = function(char) {
var arr = new Array();
arr[0] = this.substring(0, this.indexOf(char));
arr[1] = this.substring(this.indexOf(char) + 1);
return arr;
}
str = 'topic, this is the message part, with, occasional commas.'
str.mySplit(',');
-> ["topic", " this is the message part, with, occasional commas."]
javascript's String.split() method is broken (at least if you're expecting the same behavior that other language's split() methods provide).
An example of this behavior:
console.log('a,b,c'.split(',', 2))
> ['a', 'b']
and not
> ['a', 'b,c']
like you'd expect.
Try this split function instead:
function extended_split(str, separator, max) {
var out = [],
index = 0,
next;
while (!max || out.length < max - 1 ) {
next = str.indexOf(separator, index);
if (next === -1) {
break;
}
out.push(str.substring(index, next));
index = next + separator.length;
}
out.push(str.substring(index));
return out;
};
var a = whole_message.split(",");
var topic = a.splice (0,1);
(unless you like doing things complicated ways)
Why not split by comma, take the [0] item as topic then remove the topic(+,) from the original string ?
You could:
var topic = whole_message.split(",")[0]
(using prototype.js)
var message = whole_message.gsub(topic+", ", "")
(using jQuery)
whole_message.replace(topic+", ", "")
Or quicker, go with josh.trow
let string="topic, this is the message part, with occasional commas."
let arr = new Array();
let idx = string.indexOf(',')
arr[0] = string.substring(0, idx);
arr[1] = string.substring(idx+1);
let topic = arr[0];
let message = arr[1]
output arr should be: ["topic", "this is the message part, with occasional commas."]

Categories