Javascript: Split into multiple variables [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Possible to assign to multiple variables from an array?
If in python i can do this
x = "Hi there and hello there"
v1, v2, v3, v4, v5 = x.split(" ")
but im not sure how to do it in javascript..

You can turn it into an array by using javascript .split
For example
x = "Hi there and hello there";
var array = x.split(" ");
Then all your variables will be in the array like below
array[0]
array[1]
array[2]
You can show this using console.log or an alert like so.
console.log(array[0]);
alert(array[0]);
References
http://www.tizag.com/javascriptT/javascript-string-split.php

What you are asking is called "destructuring assignment" which is a feature of Javascript 1.7. Sadly, not all browsers support these JS 1.7 features (Chrome for example, executes code marked as JS 1.7 but does not yet support this feature).
Your code will work on Firefox (as long as you mark it as JS 1.7 and with a slight modification) but not on Chrome.
To see this in action, use the following with Firefox:
<script type="application/javascript;version=1.7"/>
x = "Hi there and hello there"
var [v1, v2, v3, v4, v5] = x.split(" ")
</script>

split splits the string into an array of strings.

Split returns an array.
var x = "Hi there and hello there"
var v = x.split(" ")
console.log(v[0]);
console.log(v[1]);

if you can attach the variables to an object, then you could do it this way:
var stringToWords = function (str) {
if (typeof str === "string") {
var stringsArray = str.split(" "),
stringsSet = {};
for (var i = 0, wordsNumber = stringsArray.length; i < wordsNumber; i++) {
stringsSet['str' + (i + 1)] = stringsArray[i];
}
return stringsSet;
} else {
return str + " is not a string!!!"}
};
// this will return an object with required strings
var allStringWords = stringToWords("Hi there and hello there");
//then you can access a word this way:
allStringWords.str1
but I'm sure there are shorter ways to gain the same

Related

Python's %s equivalent in Javascript?

I'm currently learning NodeJS after working with Python for the last few years.
In Python I was able to save a string inside a JSON with dynamic parameters and set them once the string loaded, for example:
MY JSON:
j = {
"dynamicText": "Hello %s, how are you?"
}
and then use my string like that:
print(j['dynamicText'] % ("Dan"))
so Python replaces the %s with "Dan".
I am looking for the JS equivalent but could not find one. Any ideas?
** Forgot to mention: I want to save the JSON as another config file so literals won't work here
Use template literal. This is comparatively new and may not support ancient browsers
var test = "Dan"
var j = {
"dynamicText": `Hello ${test}, how are you?`
}
console.log(j["dynamicText"])
Alternatively you can create a function and inside that function use string.replace method to to replace a word with new word
var test = "Dan"
var j = {
"dynamicText": "Hello %s, how are you?"
}
function replace(toReplaceText, replaceWith) {
let objText = j["dynamicText"].replace(toReplaceText, replaceWith);
return objText;
}
console.log(replace('%s', test))
There is no predefined way in JavaScript, but you could still achieve something like below. Which I have done in my existing Application.
function formatString(str, ...params) {
for (let i = 0; i < params.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
str = str.replace(reg, params[i]);
}
return str;
}
now formatString('You have {0} cars and {1} bikes', 'two', 'three') returns 'You have two cars and three bikes'
In this way if {0} repeats in String it replaces all.
like formatString('You have {0} cars, {1} bikes and {0} jeeps', 'two', 'three') to "You have two cars, three bikes and two jeeps"
Hope this helps.
You can write a String.format method, using regex, and the String.replace method:
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, (match, p1) => {
var i = parseInt(p1);
return typeof args[i] != 'undefined' ? args[i] : match;
});
}
After that, running:
console.log("{0}{1}".format("John", "Doe"));
Will output: John Doe
Of course, if you don't like editing the prototype of objects you don't own (it is generally good practice), you can just create a function:
var format = function(str) {
var args = arguments;
return str.replace(/{(\d+)}/g, (match, p1) => {
var i = parseInt(p1);
return typeof args[i+1] != 'undefined' ? args[i+1] : match;
});
}
For a few nice alternatives, you may want to take a look at JavaScript equivalent to printf/string.format
While it's asking for a C-like printf() equivalent for JS, the answers would also apply to your question, since Python format strings are inspired by C.
I've found a great npm module that does exactly what I was needed - string-format.
String-Format in NPM

Count number of times a character appears in string [duplicate]

This question already has answers here:
Count number of occurrences for each char in a string
(23 answers)
Closed 6 years ago.
So basically I need a script that summarizes which characters and the number of times they appear in a random string. Caps have to be ignored, for example:
var myString = promt ("Type anything: "); //"hello Hello";
The end result has to be something like this: h = 2, e = 2, l = 4, o = 2 printed in the HTML document.
I've tried using myString.match().length without much success. My main problem is defining which characters to check and not checking characters twice (for example: if there are two "h" in the string not checking them twice).
You can use temporary object
var o = {};
"hello Hello".toLowerCase()
.replace(/\s+/, '')
.split('')
.forEach(e => o[e] = ++o[e] || 1);
document.write(JSON.stringify(o));
This solution uses arrow function (ES2015 standard) that doesn't work in old browsers.
var str = 'hello Hello';
var count = {};
str.split('').forEach(function(v) {
if (v === ' ') return;
v = v.toLowerCase();
count[v] = count[v] ? count[v] + 1 : 1;
})
console.log(count);

Split string into two parts [duplicate]

This question already has answers here:
Split string once in javascript?
(17 answers)
Closed 8 years ago.
I know there are several ways to split an array in jQuery but I have a special case:
If I have for example this two strings:
"G09.4 What"
"A04.3 A new Code"
When I split the first by ' ' I can simply choose the code in front with [0] what would be G09.4. And when I call [1] I get the text: What
But when I do the same with the second string I get for [1] A but I want to retrieve A new Code.
So how can I retrieve for each string the code and the separate text?
Use
var someString = "A04.3 A new Code";
var index = someString.indexOf(" "); // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1); // Gets the text part
You can split the string and shift off the first entry in the returned array. Then join the leftovers e.g.
var chunks = "A04.3 A new Code".split(/\s+/);
var arr = [chunks.shift(), chunks.join(' ')];
// arr[0] = "A04.3"
// arr[1] = "A new Code"
Instead of splitting the string on the space, use a combination of indexOf and slice:
var s = "A04.3 A new Code";
var i = s.indexOf(' ');
var partOne = s.slice(0, i).trim();
var partTwo = s.slice(i + 1, s.length).trim();
You can use match() and capture what you need via a regular expression:
"G09.4 What".match(/^(\S+)\s+(.+)/)
// => ["G09.4 What", "G09.4", "What"]
"A04.3 A new Code".match(/^(\S+)\s+(.+)/)
// => ["A04.3 A new Code", "A04.3", "A new Code"]
As you can see the two items you want are in [1] and [2] of the returned arrays.
What about this one:
function split2(str, delim) {
var parts=str.split(delim);
return [parts[0], parts.splice(1,parts.length).join(delim)];
}
FIDDLE
Or for more performance, try this:
function split2s(str, delim) {
var p=str.indexOf(delim);
if (p !== -1) {
return [str.substring(0,p), str.substring(p+1)];
} else {
return [str];
}
}
You can get the code and then remove it from the original string leaving you with both the code and the string without the code.
var originalString = "A04.3 A new Code",
stringArray = originalString.split(' '),
code,
newString;
code = stringArray[0];
newString = originalString.replace(code, '');

Replacing %1 and %2 in my javascript string [duplicate]

This question already has answers here:
JavaScript equivalent to printf/String.Format
(59 answers)
Javascript multiple replace [duplicate]
Closed 9 years ago.
Lets say I have the following string in my javascript code:
var myText = 'Hello %1. How are you %2?';
Now I would like to inject something in place of %1 and %2 in the above string. I can do:
var result = myText.replace('%1', 'John').replace('%2', 'today');
I wonder if there is a better way of doing than calling 2 times the replace function.
Thanks.
How about a little format helper? That's basically what you need:
function format(str, arr) {
return str.replace(/%(\d+)/g, function(_,m) {
return arr[--m];
});
}
var myText = 'Hello %1. How are you %2?';
var values = ['John','today'];
var result = format(myText, values);
console.log(result); //=> "Hello John. How are you today?"
Demo: http://jsbin.com/uzowuw/1/edit
Try this sample
function setCharAt(str,chr,rep) {
var index = -1;
index= str.indexOf(chr);
var len= chr.length;
if(index > str.length-1) return str;
return str.substr(0,index) + rep + str.substr(index+len);
}
var myText = 'Hello %1. How are you %2?';
var result = setCharAt(myText,"%1","John");
var result = setCharAt(result,"%2","today");
alert(result);
This is meant just as a complex comment to elclarns' great answer, suggesting these alternatives:
Can be written as String.prototype
Can use arguments
The function can be altered to
String.prototype.format = function() {
var args=arguments;
return this.replace(/%(\d+)/g, function(_,m) {
return args[--m];
});
}
And called this way
var result = "I am %1, %2 years old %1".format("Jan",32);
// I am Jan, 32 years old Jan

javascript retrieve value from JSON object by matching key using Regex

I have the following javascript object literal (excerpt)
var foo = {"hello[35]":100,"goodbye[45]":42};
I have the following query:
var query = "hello"
I would like to call foo[query] to obtain the value 100, but there is a [35] for which I don't necessarily know the value of. I know for sure that I will get a unique match. Is there any way to input query is some kind of javascript regular expression? i.e.
Regex = /hello/
foo[Regex]
100
pardon the noob question...
What you have here:
var foo = {"hello[35]":100,"goodbye[45]":42};
is not JSON, which is a string representation of an object; what you have is an object literal, which creates an actual JavaScript object. As far as I know the only way to retrieve a value from an object by matching a property name with a regex is to enumerate the property names and test each one. The regex you'll need is something like:
/^hello(\[\d*\])?$/
...which will match against "hello" optionally followed by zero or more digits in square brackets. But you don't want to hard code "hello" given that you also (presumably) need the "goodbye" value, so use a function:
function getPropertyByRegex(obj,propName) {
var re = new RegExp("^" + propName + "(\\[\\d*\\])?$"),
key;
for (key in obj)
if (re.test(key))
return obj[key];
return null; // put your default "not found" return value here
}
var foo = {"hello[35]":100,"goodbye[45]":42};
alert(getPropertyByRegex(foo, "hello")); // 100
alert(getPropertyByRegex(foo, "goodbye")); // 42
alert(getPropertyByRegex(foo, "whatever")); // null (not found)
Demo: http://jsfiddle.net/asDQm/
Not sure if you can use regex without any plugins or so ...
This might help already ...
var foo = {"hello[35]":100,"goodbye[45]":42};
var query = "hello";
for(var key in foo){
if (key.indexOf(query) > -1)
document.write(foo[key]);
}
http://jsfiddle.net/3qqSr
I am noob here too but I have seen this page previously see it helps you with your question. It basically explains JSon path. Also see this question.
As your JSON is a string, you can use a regexp with this kind of statement:
var foo = '{"hello[35]":100,"goodbye[45]":42}';
var result = foo.match(/"hello\[\d*\]":\d*/g);
result = result[0].split(":")[1];
alert(result);
See it live on jsfiddle
Note that you could use a var instead of "hello" in your regexp.
var foo = {"hello[35]":100,"goodbye[45]":42};
foo = foo.replace(/\[\d+\]/g,'');
var obj = (new Function("return "+foo))();
obj.hello -> 100
obj.goodbye -> 42
var query = 'hello';
obj[query] -> 100
function getVal(s, q){
var r = s.match(new RegExp(q + "\\[\\d*\\]\":(\\d*)[\\,\\}]"));
return r?r.pop():false;
}
getVal(foo, "hello")

Categories

Resources