Formatting a constantly changing number with commas - javascript

I am trying to make an increment/idle game that constantly has changing values in terms of money. I want to be able to separate large numbers using commas. E.g 1000 becomes 1,000 and so on, all while the value is till changing.
$<span id="money">0</span>
Above shows how I am using the span tag to call the money variable from the javascript. How would I make sure that this money variable stays formatted constantly even when changing?
Edit
function formatNumber(e){
var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
val = this.value.replace(/^0+|\.|,/g,""),
res;
if (val.length) {
res = Array.prototype.reduce.call(val, (p,c) => c + p) // reverse the pure numbers string
.match(rex) // get groups in array
.reduce((p,c,i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
res += /\.|,/.test(res) ? "" : ".0"; // test if res has (.) or (,) in it
this.value = Array.prototype.reduce.call(res, (p,c) => c + p); // reverse the string and display
}
}
var mySpan = document.getElementById("money");
mySpan.addEventListener("change", formatNumber);
I have now implemented this code into my javascript but it still does not seem to be updating the variable.
Edit 2
function moneyClick(number){
money = money + number;
document.getElementById("money").innerHTML = money;
lifetimeearnings = lifetimeearnings + number;
document.getElementById("lifetimeearnings").innerHTML = lifetimeearnings;
};

Either update using some variation of what #redu pointed out whenever you calculate some changes to your money variable in the game's JavaScript, or use setInterval() to update it every 100 or so msec.

OK.. I was slightly wrong in my comment. As i understand the "change" event listener is blind to the changes at the child nodes like textContent. There is in fact this "DOMSubtreeModified" event listener that we may take use of. So;
function formatNumber(e) {
var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
val = this.textContent.replace(/^0+|\.|,/g, ""),
res;
if (val.length) {
res = Array.prototype.reduce.call(val, (p, c) => c + p) // reverse the pure numbers string
.match(rex) // get groups in array
.reduce((p, c, i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
res += /\.|,/.test(res) ? "" : ".0"; // test if res has (.) or (,) in it
this.textContent = Array.prototype.reduce.call(res, (p, c) => c + p); // reverse the string and display
}
}
var mySpan = document.getElementById("money");
mySpan.addEventListener("DOMSubtreeModified", formatNumber);
for (var i = 0; i < 10; i++) {
setTimeout(_ => mySpan.textContent = Math.floor(Math.random() * 10000000), 1000 * i);
}
<span id="money">0</span>

Related

Adding dashes to a string at certain indexes [duplicate]

I have two variables and need to insert string b into string a at the point represented by position. The result I'm looking for is "I want an apple". How can I do this with JavaScript?
var a = 'I want apple';
var b = ' an';
var position = 6;
var a = "I want apple";
var b = " an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
Optional: As a prototype method of String
The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.
if (String.prototype.splice === undefined) {
/**
* Splices text within a string.
* #param {int} offset The position to insert the text at (before)
* #param {string} text The text to insert
* #param {int} [removeCount=0] An optional number of characters to overwrite
* #returns {string} A modified string containing the spliced text.
*/
String.prototype.splice = function(offset, text, removeCount=0) {
let calculatedOffset = offset < 0 ? this.length + offset : offset;
return this.substring(0, calculatedOffset) +
text + this.substring(calculatedOffset + removeCount);
};
}
let originalText = "I want apple";
// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var output = a.substring(0, position) + b + a.substring(position);
Edit: replaced .substr with .substring because .substr is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
You can add this function to string class
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
so that you can use it on any string object:
var my_string = "abcd";
my_string.insertAt(1, "XX");
Using ES6 string literals, would be much shorter:
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
Maybe it's even better if you determine position using indexOf() like this:
function insertString(a, b, at)
{
var position = a.indexOf(at);
if (position !== -1)
{
return a.substr(0, position) + b + a.substr(position);
}
return "substring not found";
}
then call the function like this:
insertString("I want apple", "an ", "apple");
Note, that I put a space after the "an " in the function call, rather than in the return statement.
try
a.slice(0,position) + b + a.slice(position)
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.slice(0,position) + b + a.slice(position);
console.log(r);
or regexp solution
"I want apple".replace(/^(.{6})/,"$1 an")
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);
console.log(r);
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
The Underscore.String library has a function that does Insert
insert(string, index, substring) => string
like so
insert("I want apple", 6, " an");
// => "I want an apple"
If ES2018's lookbehind is available, one more regexp solution, that makes use of it to "replace" at a zero-width position after the Nth character (similar to #Kamil Kiełczewski's, but without storing the initial characters in a capturing group):
"I want apple".replace(/(?<=^.{6})/, " an")
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);
console.log(r);
console.log("I want apple".replace(/(?<=^.{6})/, " an"));
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
This would be slower, but will take care of the addition of space before and after the an
Also, you'll have to change the value of position ( to 2, it's more intuitive now)
Quick fix! If you don't want to manually add a space, you can do this:
var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
console.log(output);
(edit: i see that this is actually answered above, sorry!)
Well just a small change 'cause the above solution outputs
"I want anapple"
instead of
"I want an apple"
To get the output as
"I want an apple"
use the following modified code
var output = a.substr(0, position) + " " + b + a.substr(position);
With RegExp replace
var a = 'I want apple';
var b = ' an';
var position = 6;
var output = a.replace(new RegExp(`^(.{${position}})(.*)`), `$1${b}$2`);
console.log(output);
Info:
String.prototype.replace()
RegExp

javascript replace random letters with underscore

I want to write this google spreadsheet javascript code to replace random letters in a string.
I have created a code that does it but not randomly, plus it also replaces the spaces with an underscore (which is problematic).
The end result I'm interested in is to go from this (the sentences are in French btw.):
'J’habite à New York.'
to this:
'_’h_b_t_ à _ew _or_.'
Let's say that given a sentences, at least half of the number of letters must be replaced with an underscore.
Thank you for your help. (ps: i'm not a programmer)
The code I have so far:
var v = [['J’habite à New York.', 'Sì', ], ['Je m’appelle John. !']];
for (var r in v){
for (var c in v[r]){
var d = v[r][c];
var l = d.length;
var u = l;
while(u > 0){
var res = d.replace(d[u-2], '_');
d = res;
u = u - 2;
}
console.log(res);
}
}
You might try something like this :)
var a = "Text i want to replace text from";
var splitted = a.split('');
var count = 0; // variable where i keep trace of how many _ i have inserted
while(count < a.length/2) {
var index = Math.floor(Math.random()*a.length); //generate new index
if(splitted[index] !== '_' && splitted[index] !== ' ') {
splitted[index] = '_';
count++;
}
}
var newstring = splitted.join(""); //the new string with spaces replaced
EDIT: i tried it now on console and seems to be working. What problem does it give to you?
2° EDIT: you could do:
splitted[index] = ' _ ';
instead of
splitted[index] = '_';
also notice that i changed the if condition from:
if(splitted[index] !== '_')
to
if(splitted[index] !== '_' && splitted[index] !== ' ')
to avoid replacing empty spaces with '_'
:)
You are overcomplicatig a bit. Just turn the string into an array of characters, then map it to an array of characters with some letters replaced and turn it back into a string.
function replace(str) {
return str.split("").map(char => Math.random() > 0.5 ? "_" : char).join("");
}
var v = [
['J’habite à New York.', 'Sì', ],
['Je m’appelle John. !', 'Non!',]
];
for (const pair of v) {
pair[0] = replace(pair[0]);
pair[1] = replace(pair[1]);
}
console.log(v)

Javascript array remove odd commas

I need to create a string like this to make works the mapserver request:
filterobj = "POLYGON((507343.9 182730.8, 507560.2 182725.19999999998, 507568.60000000003 182541.1, 507307.5 182563.5, 507343.9 182730.8))";
Where the numbers are map coordinates x y of a polygon, the problem is with Javascript and OpenLayer what I have back is an array of numbers, How can I remove just the ODD commas (first, third, fifth...)?
At the moment I've created the string in this way:
filterobj = "POLYGON((" +
Dsource.getFeatures()[0].getGeometry().getCoordinates() + " ))";
And the result is:
POLYGON((507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8));
It's almost what I need but, I need to remove the ODD commas from the Dsource.getFeatures()[0].getGeometry().getCoordinates() array to make the request work, how can I do that?
The format that you need is WKT, and OpenLayers comes with a class that allows you to parse its geometries as WKT easily, as below:
var wktFormatter = new ol.format.WKT();
var formatted = wktFormatter.writeFeature(Dsource.getFeatures()[0]);
console.log(formatted); // POLYGON((1189894.0370893013 -2887048.988883849,3851097.783993299...
Look at code snippet :
Help method : setCharAt ,
Take all commas ,
take all odds commas with i % 2 == 0
// I need to start from somewhere
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var POLYGON = [507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8];
var REZ = "";
REZ = POLYGON.toString();
var all_comma = [];
for(var i=0; i<REZ.length;i++) {
if (REZ[i] === ",") all_comma.push(i);
}
for(var i=0; i<all_comma.length;i++) {
if (i % 2 == 0 ) {
REZ = setCharAt(REZ,all_comma[i],' ');
}
}
console.log(REZ);
// let return nee element intro POLYGON
// reset
POLYGON = REZ.split(',');
console.log(POLYGON);
What about this:
const str = Dsource.getFeatures()[0].getGeometry().getCoordinates()
// str = "1,2,3,4,5,6"
str.split(',').map((v, i) => {
return (i % 2) ? v : v + ','
}).join(' ')
// "1, 2 3, 4 5, 6"
There are a couple of ways to go, both involve getting rid of whitespace first. The first matches coordinate pairs, removes the comma, then pastes them back together.
The second splits into individual numbers, then formats them with reduce. Both should be ECMA-262 ed5 (2011) compatible but I don't have an old enough browser to test them.
var s = '507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8';
var re = /\d+\.?\d*,\d+\.?\d*/g;
// Solution 1
var x = s.replace(/\s/g,'').match(re).map(function(x){return x.replace(',',' ')}).join();
console.log(x);
// Solution 2
var t = s.replace(/\s/g,'').split(',').reduce(function (acc, v, i) {
i%2? (acc[acc.length - 1] += ' ' + v) : acc.push(v);
return acc;
}, []).join(',');
console.log(t);
One approach would be using Array.reduce():
var input = '1.0, 2.0, 3.0, 4.0, 5.0, 6.0';
var output = input
.split(',')
.reduce((arr, num, idx) => {
arr.push(idx % 2 ? arr.pop() + ' ' + num : num);
return arr;
}, [])
.join(',');
// output = '1.0 2.0, 3.0 4.0, 5.0 6.0'

How do I do division with reduce function?

So I am trying to divide a list of number and here is the code for it.
var myArray = document.getElementById("listInput").value.split(" ");
I took the value from the box "listInput" and I split it so it's easier to divide. Then:
for(i=0;i<myArray.length; i+=1){
if(myArray[i] === "divide")
Up here I made a for loop so the program would go through each splitted word until it finds the string "divide." After that:
{
document.getElementById("resultNumberTotal").value =
myArray.reduce(function(total, curr) {
if (!isNaN(Number(curr))) {
total = Number(curr) /total ;
}
return total;
}, 1);
}
}
}
Up in this code, the box where I want to show the result "resultNumberTotal", I made it equal to a ".reduce function" as u can. I recently learnt .reduce is a good way to add/multiply/divide so. I have 2 parameters. The program goes through the loop, finds a number(curr) then finds the command "divide" then finds another number called "total and evaluated the answer for example:
[9 divide 3] = 9/3 = 3 or [1 divide 10] = 1/10 = 1
What am I doing wrong. Plz help me understand as well Thank you
Here's an example that uses a regular expression to extract the different parts of the calculation from the string in the input element.
One of the things it extracts is the operation which needs to be done and our function uses this value to perform the calculation and return the result.
I'm not sure this is exactly what you need, but I think this is one way to solve your problem.
const input = document.getElementById("listInput");
const output = document.getElementById("resultNumberTotal");
const regex = /(\d+)\s+(divide|add|multiply|subtract)\s+(\d+)/g;
input.onchange = function(ev) {
output.value = check(input.value);
}
function check(str) {
let m = regex.exec(str);
if (m == null || m.length < 4) {
return ''
}
const a = m[1],
b = m[3],
op = m[2];
let res = NaN;
switch (op) {
case 'divide':
res = a / b;
break;
case 'add':
res = a + b;
break;
case 'multiply':
res = a * b;
break;
case 'subtract':
res = a - b;
break;
}
return '[' + a + ' ' + op + ' ' + b + '] = ' + res
}
<input type="text" id="listInput" />
<input type="text" id="resultNumberTotal" />

How to add a space in a specific index of a string? [duplicate]

How can I insert a string at a specific index of another string?
var txt1 = "foo baz"
Suppose I want to insert "bar " after the "foo" how can I achieve that?
I thought of substring(), but there must be a simpler more straight forward way.
Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
You could prototype your own splice() into String.
Polyfill
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* #this {String}
* #param {number} start Index at which to start changing the string.
* #param {number} delCount An integer indicating the number of old chars to remove.
* #param {string} newSubStr The String that is spliced in.
* #return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
Example
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"
EDIT: Modified it to ensure that rem is an absolute value.
Here is a method I wrote that behaves like all other programming languages:
String.prototype.insert = function(index, string) {
if (index > 0)
{
return this.substring(0, index) + string + this.substring(index, this.length);
}
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
Reference:
http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/
Just make the following function:
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}
and then use it like that:
alert(insert("foo baz", 4, "bar "));
Output: foo bar baz
It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).
NOTE: This insert function inserts the string value (third parameter) before the specified integer index (second parameter) in the string str (first parameter), and then returns the new string without changing str!
UPDATE 2016: Here is another just-for-fun (but more serious!) prototype function based on one-liner RegExp approach (with prepend support on undefined or negative index):
/**
* Insert `what` to string at position `index`.
*/
String.prototype.insert = function(what, index) {
return index > 0
? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
: what + this;
};
console.log( 'foo baz'.insert('bar ', 4) ); // "foo bar baz"
console.log( 'foo baz'.insert('bar ') ); // "bar foo baz"
Previous (back to 2012) just-for-fun solution:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
This is basically doing what #Base33 is doing except I'm also giving the option of using a negative index to count from the end. Kind of like the substr method allows.
// use a negative index to insert relative to the end of the string.
String.prototype.insert = function (index, string) {
var ind = index < 0 ? this.length + index : index;
return this.substring(0, ind) + string + this.substr(ind);
};
Example:
Let's say you have full size images using a naming convention but can't update the data to also provide thumbnail urls.
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
If anyone is looking for a way to insert text at multiple indices in a string, try this out:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
For example, you can use this to insert <span> tags at certain offsets in a string:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
Instantiate an array from the string
Use Array#splice
Stringify again using Array#join
The benefits of this approach are two-fold:
Simple
Unicode code point compliant
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
Given your current example you could achieve the result by either
var txt2 = txt1.split(' ').join(' bar ')
or
var txt2 = txt1.replace(' ', ' bar ');
but given that you can make such assumptions, you might as well skip directly to Gullen's example.
In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
https://jsfiddle.net/gaby_de_wilde/wz69nw9k/
I know this is an old thread, however, here is a really effective approach.
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.
Were you to need a string, simply access the node's text content property.
tn.textContent
#=> "I am just trying to help"
You can do it easily with regexp in one line of code
const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
console.log(res);
"Hello Lovely RegExp!"
Well, we can use both the substring and slice method.
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
The only problem of a substring method is that it won't work with a negative index. It's always take string index from 0th position.
You can use Regular Expressions with a dynamic pattern.
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
outputs:
"something "
This replaces text.length of whitespace characters at the beginning of the string output.
The RegExp means ^\ - beginning of a line \s any white space character, repeated {n} times, in this case text.length. Use \\ to \ escape backslashes when building this kind of patterns out of strings.
another solution, cut the string in 2 and put a string in between.
var str = jQuery('#selector').text();
var strlength = str.length;
strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);
jQuery('#selector').html(strf + 'inserted' + strb);
Using slice
You can use slice(0,index) + str + slice(index). Or you can create a method for it.
String.prototype.insertAt = function(index,str){
return this.slice(0,index) + str + this.slice(index)
}
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
Splice method for Strings
You can split() the main string and add then use normal splice()
String.prototype.splice = function(index,del,...newStrs){
let str = this.split('');
str.splice(index,del,newStrs.join('') || '');
return str.join('');
}
var txt1 = "foo baz"
//inserting single string.
console.log(txt1.splice(4,0,"bar ")); //foo bar baz
//inserting multiple strings
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz
//removing letters
console.log(txt1.splice(1,2)) //f baz
//remving and inseting atm
console.log(txt1.splice(1,2," bar")) //f bar baz
Applying splice() at multiple indexes
The method takes an array of arrays each element of array representing a single splice().
String.prototype.splice = function(index,del,...newStrs){
let str = this.split('');
str.splice(index,del,newStrs.join('') || '');
return str.join('');
}
String.prototype.mulSplice = function(arr){
str = this
let dif = 0;
arr.forEach(x => {
x[2] === x[2] || [];
x[1] === x[1] || 0;
str = str.splice(x[0] + dif,x[1],...x[2]);
dif += x[2].join('').length - x[1];
})
return str;
}
let txt = "foo bar baz"
//Replacing the 'foo' and 'bar' with 'something1' ,'another'
console.log(txt.splice(0,3,'something'))
console.log(txt.mulSplice(
[
[0,3,["something1"]],
[4,3,["another"]]
]
))
I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code
also have a look at this performance comparison, substring, slice
The code I used creates huge strings and inserts the string "bar " multiple times into the huge string
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* #this {String}
* #param {number} start Index at which to start changing the string.
* #param {number} delCount An integer indicating the number of old chars to remove.
* #param {string} newSubStr The String that is spliced in.
* #return {string} A new string with the spliced substring.
*/
String.prototype.splice = function (start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
String.prototype.splice = function (idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
function createString(size) {
var s = ""
for (var i = 0; i < size; i++) {
s += "Some String "
}
return s
}
function testSubStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.insert(4, "bar ")
}
function testSpliceStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.splice(4, 0, "bar ")
}
function doTests(repeatMax, sSizeMax) {
n = 1000
sSize = 1000
for (var i = 1; i <= repeatMax; i++) {
var repeatTimes = n * (10 * i)
for (var j = 1; j <= sSizeMax; j++) {
var actualStringSize = sSize * (10 * j)
var s1 = createString(actualStringSize)
var s2 = createString(actualStringSize)
var start = performance.now()
testSubStringPerformance(s1, repeatTimes)
var end = performance.now()
var subStrPerf = end - start
start = performance.now()
testSpliceStringPerformance(s2, repeatTimes)
end = performance.now()
var splicePerf = end - start
console.log(
"string size =", "Some String ".length * actualStringSize, "\n",
"repeat count = ", repeatTimes, "\n",
"splice performance = ", splicePerf, "\n",
"substring performance = ", subStrPerf, "\n",
"difference = ", splicePerf - subStrPerf // + = splice is faster, - = subStr is faster
)
}
}
}
doTests(1, 100)
The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)
Take the solution. I have written this code in an easy format:
const insertWord = (sentence,word,index) => {
var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
for (var i = 0; i < sliceSentence.length; i++)
{
if (i === index)
{ // checking if index of array === input index
for (var j = 0; j < word.length; j++)
{ // if yes we'll insert the word
output.push(sliceWord[j]); // Condition is true we are inserting the word
}
output.push(" "); // providing a single space at the end of the word
}
output.push(sliceSentence[i]); // pushing the remaining elements present in an array
}
join = output.join(""); // converting an array to string
console.log(join)
return join;
}
Prototype should be the best approach as many mentioned. Make sure that prototype comes earlier than where it is used.
String.prototype.insert = function (x, str) {
return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};

Categories

Resources