Generate minimum number of sets of substrings with max substring length - javascript

Given a string, I'd like to create the minimum number of sets of substrings where:
substrings have a length up to x
if two sets differ when a substring in one set can be composed of smaller substrings in the other set, the second set can be excluded
For example, the substring "abcdef" with max substring length of 3 would result in the following:
[
['abc','def'],
['ab','cde','f'],
['ab','cd','ef'],
['a','bcd','ef'],
]
['abc','de','f'] is not included because of condition (2). eg, 'def' is compsed of 'de','f'
The following recursive allSubstrings() method isn't quite right and doesn't feel like the right approach. Also has the problem of being slow with longer strings.
const allSubstrings = (input,max_len = 3) => {
if( input.length === 1) return [[input]];
let result = [];
const start = input.substring(1);
allSubstrings(start).forEach(function(subresult) {
let tmp = subresult.slice(0);
if( tmp[0].length < max_len ){
tmp[0] = input.charAt(0) + tmp[0];
result.push(tmp);
}
if( subresult.length > 1 ){
if( subresult.slice(0,2).join('').length <= max_len ){
return;
}
if( subresult.slice(subresult.length-2).join('').length <= max_len ){
return;
}
}
tmp = subresult.slice(0);
tmp.unshift(input.charAt(0));
result.push(tmp);
});
return result;
}

Here's one possible approach using recursion, not optimized for performance (e.g., there's no memoization):
function splits(s: string, maxLen: number, minInitLen: number = 1): string[][] {
const ret: string[][] = s.length ? [] : [[]];
for (let i = Math.min(maxLen, s.length); i >= minInitLen; i--) {
for (const r of splits(s.slice(i), maxLen, maxLen + 1 - i)) {
ret.push([s.slice(0, i), ...r]);
}
}
return ret;
}
The idea is that splits() takes not just the string s to split and the maximum length maxLen of substrings, but also the minimum allowable length minInitLen for the first substring. When you start splitting the string this initial length is 1, but inside the recursion it could be larger. After all, let's say that you've split "abcdef" into "a" so far. Now you need to split "bcdef", but the next substring has to have length 3 ("bcd"), since "b" would collapse into "ab" and "bc" would collapse into "abc". If you've split it into "ab" so far, then the next substring has to have length at least 2 ("cd" or "cde"), since "c" would collapse into "abc". The relevant math is that if the current substring is of length i, then the next substring must have at least length maxLen + 1 - i.
The base case for the recursion is when you are asked to split an empty string. In this case you want to return [[]]; there is exactly one way to split an empty string. If you are splitting a non-empty string then you want to iterate your first substring length i between minInitLen and maxLen (well, you can't exceed s.length either), and calculate the recursive result splits(s.slice(i), maxLen, maxLen + 1 - i), and then for each set of strings in the result, prepend the initial substring s.slice(0, i) to it.
Let's see if it works:
console.log(splits("abcdef", 3))
// [["abc", "def"], ["ab", "cde", "f"], ["ab", "cd", "ef"], ["a", "bcd", "ef"]]
console.log(splits("abcdefgh", 5))
// [["abcde", "fgh"], ["abcd", "efgh"], ["abc", "defgh"], ["ab", "cdefg", "h"],
// ["ab", "cdef", "gh"], ["a", "bcdef", "gh"]]
It looks good, at least for your example input. I'm not sure if there are edge cases, or if performance becomes a problem for large strings (it probably depends very much on what "large" means). And one could certainly refactor to use functional programming array methods instead of for loops if one wanted. But at least it works.
Playground link to code

Related

JavaScript function receives two strings and returns n

I've been trying to complete this challenge recently but with no success, tried many ways but
for some reason I don't manage to complete all the examples below.
I will be appreciated if someone can assist me with that, showing me step by step.
Write a function that receives two strings and returns n, where n is
equal to the number of characters we should shift the first string
forward to match the second. For instance, take the strings "fatigue"
and "tiguefa". In this case, the first string has been rotated 5
characters forward to produce the second string, so 5 would be
returned.
If the second string isn't a valid rotation of the first string, the
method returns -1. Specification shiftedDiff(first, second) provide
amount of rotations to match words
Parameters first: String - word to be matched
second: String - word to be checked
Return Value Number - Number of rotations, nil or -1 if invalid
Examples:
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
function shiftedDiff(first, second) {
// Split the second word into an array for
// easier manipulation
const arr = [...second];
// Iterate over the array
for (let i = 0; i < arr.length; i++) {
// If the first and joined array match
// return the index
if (first === arr.join('')) return i;
// Otherwise `shift` off the first element of `arr`
// and `push` it on the end of the array
arr.push(arr.shift());
}
// If there are no matches return -1
return -1;
}
console.log(shiftedDiff('coffee', 'eecoff')); // 2
console.log(shiftedDiff('eecoff', 'coffee')); // 4
console.log(shiftedDiff('moose', 'Moose')); // -1
console.log(shiftedDiff("isn't", "'tisn")); // 2
console.log(shiftedDiff('Esham', 'Esham')); // 0
console.log(shiftedDiff('dog', 'god')); // -1
Documentation
push
shift
Spread syntax
let shiftedDiff = (f, s) => {
let r = -1;
f.split('').forEach((e, i) => {
f = f.substr(1) + e;
if (f == s) r = f.length - (i + 1)
})
return r;
}
console.log(shiftedDiff("coffee", "eecoff"))
console.log(shiftedDiff("eecoff", "coffee"))
console.log(shiftedDiff("moose", "Moose"))
console.log(shiftedDiff("isn't", "'tisn"))
console.log(shiftedDiff("Esham", "Esham"))
console.log(shiftedDiff("dog", "god"))

Square every digit of a number

I am trying to learn JavaScript but find it to be a bit confusing. I am trying to square every digit of a number
For example: run 9119 through the function, 811181 will come out, because 9^2 is 81 and 1^2 is 1.
My code:
function squareDigits(num){
return Math.pow(num[0],2) && Math.pow(num[1],2);
}
Correct code:
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
I do not know why .map, .split, and .join was used to answer the question.
.split takes a string and splits it into an array based on the character(s) passed to it '' in this case.
So
("9119").split('') === ["9", "1", "1", "9"]
.map works like a for loop but takes a function as an argument. That function is applied to every member of the array.
So
["9", "1", "1", "9"].map(function(val) { return val * val;}) === ["81", "1", "1", "81"]
.join does the opposite of .split. It takes an Array and concatenates it into a string based on the character(s) passed to it.
So
["81", "1", "1", "81"].join('') === "811181"
Additionally, the && operator checks to see if the expressions on either side of it evaluate to true. If both expressions evaluate to true, only then will it return true. It always returns a Boolean though. I think you wanted to convert your values to string first using Number.toString() and then append them together using the + operator
return Math.pow(num[0],2).toString() + Math.pow(num[1],2).toString();
function squareDigits(num) {
// Convert the result to a number. "252525" -> 252525
return Number(
num.toString() // num === "555"
.split('') // ["5", "5", "5"]
.map(elem => elem * elem) "5" * "5" === 25 (Type coversion)
// Now we have [25, 25, 25]
.join('') // "252525"
);
}
squareDigits(555);
There are several methods of this, but the first that comes to mind is to pass the number as a string, split it, then parse the numbers, square them individually, make them strings, and paste them back together, it sounds complex but makes sense once you see it
//function takes number as an argument
function convertNumber(num){
//the toString method converts a number into a string
var number = num.toString();
//the split method splits the string into individual numbers
var arr = number.split("");
//this variable will hold the numbers that we square later
var squaredArr = [];
//the for loop iterates through everything in our array
for(var i=0; i<arr.length; i++){
//parseInt turns a string into a number
var int = parseInt(arr[i]);
//Math.pow raises integers to a given exponent, in this case 2
int = Math.pow(int, 2);
//we push the number we just made into our squared array as a string
squaredArr.push(int.toString());
}
//the function returns the numbers in the squared array after joining
//them together. You could also parseInt the array if you wanted, doing
//this as parseInt(squaredArr[0]); (this would be done after joining)
return squaredArr.join('');
}
Basically you need single digits for getting squared values.
You could take Array.from, which splits a string (which is a type with an implemented Symbol.iterator) into characters and uses an optional maping for the values.
function sqare(number) {
return +Array.from(number.toString(), v => v * v).join('');
}
console.log(sqare(9119));
try these code..
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.

Firebase: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string

Considering a ref with children whose keys are numbers (so that with orderByKey "Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order")
Doing:
ref.orderByKey().startAt(5)
I am getting the following error:
When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string
In the documentation for startAt I see:
When used in combination with orderByKey(), the value must be a string.
Can I replace this with ref.orderByKey().startAt("5")? Will that still run startAt using numerical rather than lexicographical order?
All Firebase keys are strings. If you are using implicit array coercion with numeric keys, you should strongly consider switching to position as a child property. So not:
0: {foo: 'bar'}
But:
-Kpushidgoeshere: {position: 0, foo: 'bar'}
Then you would do orderByChild('position').startAt(5) to achieve the desired result of sorting by position. Numeric key strings are inefficient and generally difficult to work with in Firebase.
In the firepad code I found methods to convert a number to/from a lexicographical string so they can safely be used as keys:
let characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// numerical to a lexigaraphically ordered string
function revisionToId(revision) {
if (revision === 0) return 'A0';
let str = '';
while (revision > 0) {
let digit = (revision % characters.length);
str = characters[digit] + str;
revision -= digit;
revision /= characters.length;
}
let prefix = characters[str.length + 9]; // Prefix with length (starting at 'A' for length 1) to ensure the id's sort lexicographically.
return prefix + str;
}
// and reverse
function revisionFromId(revisionId) {
// assert(revisionId.length > 0 && revisionId[0] === characters[revisionId.length + 8]);
let revision = 0;
for (let i = 1; i < revisionId.length; i++) {
revision *= characters.length;
revision += characters.indexOf(revisionId[i]);
}
return revision;
}

Letter Count I JavaScript Challenge on Coderbyte

I've been on this problem for several hours now and have done all I can to the best of my current newbie javaScript ability to solve this challenge but I just can't figure out exactly what's wrong. I keep getting "UNEXPECTED TOKEN ILLEGAL on here: http://jsfiddle.net/6n8apjze/14/
and "TypeError: Cannot read property 'length' of null": http://goo.gl/LIz89F
I think the problem is the howManyRepeat variable. I don't understand why I'm getting it can't read the length of null when clearly word is a word from str...
I got the idea for:
word.toLowerCase().split("").sort().join("").match(/([.])\1+/g).length
...here: Get duplicate characters count in a string
The Challenge:
Using the JavaScript language, have the function LetterCountI(str) take the str
parameter being passed and return the first word with the greatest number of
repeated letters. For example: "Today, is the greatest day ever!" should return
greatest because it has 2 e's (and 2 t's) and it comes before ever which also
has 2 e's. If there are no words with repeating letters return -1. Words will
be separated by spaces.
function LetterCountI(str){
var wordsAndAmount={};
var mostRepeatLetters="-1";
var words=str.split(" ");
words.forEach(function(word){
// returns value of how many repeated letters in word.
var howManyRepeat=word.toLowerCase().split("").sort().join("").match(/([.])\1+/g).length;
// if there are repeats(at least one value).
if(howManyRepeat !== null || howManyRepeat !== 0){
wordsAndAmount[word] = howManyRepeat;
}else{
// if no words have repeats will return -1 after for in loop.
wordsAndAmount[word] = -1;
}
});
// word is the key, wordsAndAmount[word] is the value of word.
for(var word in wordsAndAmount){
// if two words have same # of repeats pick the one before it.
if(wordsAndAmount[word]===mostRepeatLetters){
mostRepeatLetters=mostRepeatLetters;
}else if(wordsAndAmount[word]<mostRepeatLetters){
mostRepeatLetters=mostRepeatLetters;
}else if(wordsAndAmount[word]>mostRepeatLetters){
mostRepeatLetters=word;
}
}
return mostRepeatLetters;
}
// TESTS
console.log("-----");
console.log(LetterCountI("Today, is the greatest day ever!"));
console.log(LetterCountI("Hello apple pie"));
console.log(LetterCountI("No words"));
Any guidance is much appreciated. Thank you!! ^____^
Here is the working code snippet:
/*
Using the JavaScript language, have the function LetterCountI(str) take the str
parameter being passed and return the first word with the greatest number of
repeated letters. For example: "Today, is the greatest day ever!" should return
greatest because it has 2 e's (and 2 t's) and it comes before ever which also
has 2 e's. If there are no words with repeating letters return -1. Words will
be separated by spaces.
console.log(LetterCountI("Today, is the greatest day ever!") === "greatest");
console.log(LetterCountI("Hello apple pie") === "Hello");
console.log(LetterCountI("No words") === -1);
Tips:
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.
We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join. We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.
When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.
/(.)\1+/g with the match method will return a value of letters that appear one after the other. Without sort(), this wouldn't work.
*/
function LetterCountI(str){
var wordsAndAmount={};
var mostRepeatLetters="";
var words=str.split(" ");
words.forEach(function(word){
var howManyRepeat=word.toLowerCase().split("").sort().join("").match(/(.)\1+/g);
if(howManyRepeat !== null && howManyRepeat !== 0){ // if there are repeats(at least one value)..
wordsAndAmount[word] = howManyRepeat;
} else{
wordsAndAmount[word] = -1; // if no words have repeats will return -1 after for in loop.
}
});
// console.log(wordsAndAmount);
for(var word in wordsAndAmount){ // word is the key, wordsAndAmount[word] is the value of word.
// console.log("Key = " + word);
// console.log("val = " + wordsAndAmount[word]);
if(wordsAndAmount[word].length>mostRepeatLetters.length){ //if two words have same # of repeats pick the one before it.
mostRepeatLetters=word;
}
}
return mostRepeatLetters ? mostRepeatLetters : -1;
}
// TESTS
console.log("-----");
console.log(LetterCountI("Today, is the greatest day ever!"));
console.log(LetterCountI("Hello apple pie"));
console.log(LetterCountI("No words"));
/*
split into words
var wordsAndAmount={};
var mostRepeatLetters=0;
loop through words
Check if words has repeated letters, if so
Push amount into object
Like wordsAndAmount[word[i]]= a number
If no repeated letters...no else.
Loop through objects
Compare new words amount of repeated letters with mostRepeatLetters replacing whoever has more.
In the end return the result of the word having most repeated letters
If all words have no repeated letters return -1, ie.
*/
The changes made:
[.] turned into . as [.] matches a literal period symbol, not any character but a newline
added closing */ at the end of the code (the last comment block was not closed resulting in UNEXPECTED TOKEN ILLEGAL)
if(howManyRepeat !== null || howManyRepeat !== 0) should be replaced with if(howManyRepeat !== null && howManyRepeat !== 0) since otherwise the null was testing for equality with 0 and led to the TypeError: Cannot read property 'length' of null" issue. Note that .match(/(.)\1+/g).length cannot be used since the result of matching can be null, and this will also cause the TypeError to appear.
The algorithm for getting the first entry with the greatest number of repetitions was wrong since the first if block allowed subsequent entry to be output as a correct result (not the first, but the last entry with the same repetitions was output actually)
-1 can be returned if mostRepeatLetters is empty.
Hope you dont mind if I rewrite this code. My code may not be that efficient.
Here is a snippet
function findGreatest() {
// ipField is input field
var getString = document.getElementById('ipField').value.toLowerCase();
var finalArray = [];
var strArray = [];
var tempArray = [];
strArray = (getString.split(" "));
// Take only those words which has repeated letter
for (var i = 0, j = strArray.length; i < j; i++) {
if ((/([a-zA-Z]).*?\1/).test(strArray[i])) {
tempArray.push(strArray[i]);
}
}
if (tempArray.length == 0) { // If no word with repeated Character
console.log('No such Word');
return -1;
} else { // If array has words with repeated character
for (var x = 0, y = tempArray.length; x < y; x++) {
var m = findRepWord(tempArray[x]); // Find number of repeated character in it
finalArray.push({
name: tempArray[x],
repeat: m
})
}
// Sort this array to get word with largest repeated chars
finalArray.sort(function(z, a) {
return a.repeat - z.repeat
})
document.getElementById('repWord').textContent=finalArray[0].name;
}
}
// Function to find the word which as highest repeated character(s)
function findRepWord(str) {
try {
return str.match(/(.)\1+/g).length;
} catch (e) {
return 0;
} // if TypeError
}
Here is DEMO
function LetterCountI(str) {
var word_arr = str.split(" ");
var x = word_arr.slice();
for(var i = 0; i < x.length; i ++){
var sum = 0;
for(var y = 0; y < x[i].length; y++){
var amount = x[i].split("").filter(function(a){return a == x[i][y]}).length;
if (amount > 1){
sum += amount
}
}
x[i] = sum;
}
var max = Math.max.apply(Math,x);
if(max == 0)
return -1;
var index = x.indexOf(max);
return(word_arr[index]);
};
Here is another version as well.
You could use new Set in the following manner:
const letterCount = s => {
const res = s.split(' ')
.map(s => [s, (s.length - new Set([...s]).size)])
.reduce((p, c) => (!p.length) ? c
: (c[1] > p[1]) ? c : p, []);
return !res[1] ? -1 : res.slice(0,1).toString()
}
Note: I have not tested this solution (other than the phrases presented here), but the idea is to subtract unique characters from the total characters in each word of the phrase.

Is there a splice method for strings?

The Javascript splice only works with arrays. Is there similar method for strings? Or should I create my own custom function?
The substr(), and substring() methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace() will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice() method. I tried converting my string to an array, but this is not a neat method.
It is faster to slice the string twice, like this:
function spliceSlice(str, index, count, add) {
// We cannot pass negative indexes directly to the 2nd slicing operation.
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
than using a split followed by a join (Kumar Harsh's method), like this:
function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}
Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)
Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.
Edit
This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.
No, there is no such thing as a String.splice, but you can try this:
newStr = str.split(''); // or newStr = [...str];
newStr.splice(2,5);
newStr = newStr.join('');
I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...
Here's a nice little Curry which lends better readability (IMHO):
The second function's signature is identical to the Array.prototype.splice method.
function mutate(s) {
return function splice() {
var a = s.split('');
Array.prototype.splice.apply(a, arguments);
return a.join('');
};
}
mutate('101')(1, 1, '1');
I know there's already an accepted answer, but hope this is useful.
There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.
Clarification
From "string.splice" one may expect that it, like the one for arrays:
accepts up to 3 arguments: start position, length and (optionally) insertion (string)
returns the cut out part
modifies the original string
The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:
In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.
So, with that in account, one may expect the "string.splice" thing to only:
accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)
returns the cut out part
which is what substr does; or, alternatively,
accepts up to 3 arguments: start position, length and (optionally) insertion (string)
returns the modified string (without the cut part and with insertion)
which is the subject of the next section.
Solutions
If you care about optimizing, you should probably use the Mike's implementation:
String.prototype.splice = function(index, count, add) {
if (index < 0) {
index += this.length;
if (index < 0)
index = 0;
}
return this.slice(0, index) + (add || "") + this.slice(index + count);
}
Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:
if (index < 0) {
index += this.length;
if (index < 0)
index = 0;
}
if (index >= this.length) {
index -= this.length;
if (index >= this.length)
index = this.length - 1;
}
or even
index = index % this.length;
if (index < 0)
index = this.length + index;
If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:
String.prototype.splice = function(index, count, add) {
var chars = this.split('');
chars.splice(index, count, add);
return chars.join('');
}
Performance
The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:
10 letters 100 letters 1000 letters
slice implementation 1.25 M 2.00 M 1.91 M
split implementation 0.63 M 0.22 M 0.04 M
note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).
I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).
String.prototype.splice = function(startIndex,length,insertString){
return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
};
You can use it like this:
var creditCardNumber = "5500000000000004";
var cardSuffix = creditCardNumber.splice(0,12,'****');
console.log(cardSuffix); // output: ****0004
See Test Results:
https://jsfiddle.net/0quz9q9m/5/
Simply use substr for string
ex.
var str = "Hello world!";
var res = str.substr(1, str.length);
Result = ello world!
The method Louis's answer, as a String prototype function:
String.prototype.splice = function(index, count, add) {
if (index < 0) {
index = this.length + index;
if (index < 0) {
index = 0;
}
}
return this.slice(0, index) + (add || "") + this.slice(index + count);
}
Example:
> "Held!".splice(3,0,"lo Worl")
< "Hello World!"
So, whatever adding splice method to a String prototype cant work transparent to spec...
Let's do some one extend it:
String.prototype.splice = function(...a){
for(var r = '', p = 0, i = 1; i < a.length; i+=3)
r+= this.slice(p, p=a[i-1]) + (a[i+1]||'') + this.slice(p+a[i], p=a[i+2]||this.length);
return r;
}
Every 3 args group "inserting" in splice style.
Special if there is more then one 3 args group, the end off each cut will be the start of next.
'0123456789'.splice(4,1,'fourth',8,1,'eighth'); //return '0123fourth567eighth9'
You can drop or zeroing the last arg in each group (that treated as "nothing to insert")
'0123456789'.splice(-4,2); //return '0123459'
You can drop all except 1st arg in last group (that treated as "cut all after 1st arg position")
'0123456789'.splice(0,2,null,3,1,null,5,2,'/',8); //return '24/7'
if You pass multiple, you MUST check the sort of the positions left-to-right order by youreself!
And if you dont want you MUST DO NOT use it like this:
'0123456789'.splice(4,-3,'what?'); //return "0123what?123456789"
Louis's spliceSlice method fails when add value is 0 or other falsy values, here is a fix:
function spliceSlice(str, index, count, add) {
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}
const hasAdd = typeof add !== 'undefined';
return str.slice(0, index) + (hasAdd ? add : '') + str.slice(index + count);
}
I solved my problem using this code, is a somewhat replacement for the missing splice.
let str = "I need to remove a character from this";
let pos = str.indexOf("character")
if(pos>-1){
let result = str.slice(0, pos-2) + str.slice(pos, str.length);
console.log(result) //I need to remove character from this
}
I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos

Categories

Resources