javascript: how to save string substitution in another string? [duplicate] - javascript

This question already has answers here:
JavaScript equivalent to printf/String.Format
(59 answers)
Closed 1 year ago.
I have a string and array
var s1 = "hello %s, i am %d years old";
var s2 =[John,24];
Expected result:
s3 = hello John i am 24 years old
I want to save the output into another string.
I'm able to display output in console
console.log(s1, ...s2)
But not able to store in other string.
I tried many things like:
var s3 = s1.format(...s2)
Any suggestions?

Unfortunately there is no string formatter available in JS, you'd have to write that manually like
let i = 0;
s3 = s1.replace(/%(s|d)/g, (_, type) => s2[i++]);

You could use the template string from ES6:
let anotherString = `Hello ${s2[0]}, I am ${s2[1]} years old`;
You could use this too:
String.prototype.format = function() {
a = this;
for (k in arguments) {
a = a.replace("{" + k + "}", arguments[k])
}
return a
}
Usage:
let anotherString = '{0} {1}!'.format('Hello', 'Word');
Than those solutions I dont see any other way to do that.

Related

Why is array[0] = array[0].toUpperCase() working, while array[0][0] = array[0][0].toUpperCase() isn't [duplicate]

This question already has answers here:
string.charAt(x) or string[x]?
(7 answers)
Capitalize words in string [duplicate]
(21 answers)
Closed 4 years ago.
TO BE CLEAR:
I don't want to know how to capitalize, but rather I want to know why i can change it in one-dimensional, but not 2-dimensional
I'm doing some coding challenges to get familiar with JavaScript.
I capitalized the first Letter of each word in a given string.
I split the string into a word-seperated array via String.match(regex);
var word_array = str.match(/\w(\w)*/g);
And I then made from the word another letter-seperated array to change single letters. (also with regex)
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
And this works just fine.
But I wanted it a bit shorter, so I tried to do the action on the letter on the second dimension of the word_array, but with no effect at all.
word_array[i][0] = word_array[i][0].toUpperCase();
Full-Code-Snippet
const input = document.querySelector("#string"),
button = document.querySelector("#DOIT");
button.addEventListener("click", function(){
LetterCapitalize(input.value);
});
function LetterCapitalize(str) {
var word_array = str.match(/\w(\w)*/g);
for(let i = 0; i < word_array.length; i++){
//This part works
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
word_array[i] = letter_array.join("");
//this doesn't
/*
word_array[i][0] = word_array[i][0].toUpperCase();
console.log(word_array[i][0]);
*/
}
console.log(word_array);
str = word_array.join(" ");
return str;
}
<input id="string" type="text"/>
<button id="DOIT">DO IT</button>
This wouldnt work wouldn't work since Strings are immutable in javascript. the
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
code snipped worked as you converted your strings to a list/array which is mutable by nature. although, id like to point out that this question might be a duplicate. here is a capitalization in javascript question

Split a string into two using pure javascript [duplicate]

This question already has answers here:
How to use split?
(4 answers)
Closed 7 years ago.
I have a string like this 132+456 or 132-456 or 132*456..etc ,it changes dynamically but I need to split this into 132 and 456 how to do it using pure java script?
It should be as easy as:
var parts = '132+456'.split('+');
parts[0]; //132
parts[1]; //456
Like so
var data = '132+456'.split('+');
var a = data[0];
var b = data[1];
// document.writeln only for example
document.writeln(a);
document.writeln(b);
Java
String[] values='132+456'.split('+');
String firstPart=value[0]; // has 132
for js
var data = '132+456'.split('+');
var a = data[0];
var b = data[1];

In this example how would I make filenames appended with "0000"+1 instead of "0"+1? [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 years ago.
I know this is a gimme, but I'm trying to make the filenames serialized with four digits instead of one. This function is for exporting PNG files from layers within Adobe Illustrator. Let me know if you ever need icons - much respect.
var n = document.layers.length;
hideAllLayers ();
for(var i=n-1, k=0; i>=0; i--, k++)
{
//hideAllLayers();
var layer = document.layers[i];
layer.visible = true;
var file = new File(folder.fsName + '/' +filename+ '-' + k +".png");
document.exportFile(file,ExportType.PNG24,options);
layer.visible = false;
}
Use util.printf (see the Acrobat API, page 720):
var file = new File(util.printf("%s/%s-%04d.png", folder.fsName, filename, k));
You can pad your number to the left and take the last four characters like this:
var i = 9;
var num = ("0000"+i);
var str = "filename"+(num.substring(num.length-4)); //filename0009
Or shorter
str = ("0000" + i).slice(-4)
Thanks to this question

How to detect image file extension in a string with JavaScript [duplicate]

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 9 years ago.
I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.
Use lastIndexOf()
var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);
Fiddle
You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.
'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]
var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];
Try this.
function searchText(text)
{
var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/");
for (var i=0; i<arr.length; i++)
{
//Make tags where 'arr[i]' is your url.
}
}
HINT: (Please use logic based on your needs)
you have to split string somehow based on your condition and check if the string has . or something
var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' ');
if text array has your condition then assign to variable filename
if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}
separate the extension
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}

getting parameter from url [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Get escaped URL parameter
(19 answers)
Closed 9 years ago.
I have this url index.html#secondPage?name=the%20second%20page
I want to get the value of name ("the second page") using javascript and jquery
thanks
You can use the code from the answers to this question. The only difference is that you want to parse the location.hash instead of location.search so just change that in whichever answer you choose to go with.
You'll also need to use substr to delete the leading # like:
var hash = window.location.hash.substr(1);
Here is the code from my answer to the question I linked to, with the modification:
function get_query(){
var url = location.hash.substr(1);
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
You can use it like:
var secondPage = get_query()['name']; // 'the second page'
Try like below, It will help you
Fiddle : http://jsfiddle.net/RYh7U/144/
Javascript :
function GetURLValue (sKey) {
return unescape("index.html#secondPage?name=the%20second%20page".replace(new RegExp("^(?:.*[&\\?]" + escape(sKey).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(GetURLValue("name"));

Categories