Suppose I want to generate a string base on some incremental no and a specified string.
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
Now want to replace the originalStr from last without changing its size like
//for str1 my expected output is 'activa100'
//for str2 my expected output is 'activ4569'
//for str3 my expected output is 'acti12345'
//for str4 my expected output is '123456789'
How I do this using JS?
I tried the following method:
Is their any better method than this? How to ensure result size always 9
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
const str5 = 'sizeWillChanged'
console.log(str1.padStart(9,originalStr)); //'activa100'
console.log(str2.padStart(9,originalStr)); //'activ4659'
console.log(str3.padStart(9,originalStr)); //'acti12345'
console.log(str4.padStart(9,originalStr)); //'123456789'
console.log(str5.padStart(9,originalStr)); //'sizeWillChanged'
You can use slice() to remove n characters from originalStr from the end. So that the new characters can be prefixed to originalStr without affecting the original length of originalStr.
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
function replacing(str, token) {
return (str.slice(0, -token.length) + token);
}
console.log(replacing(originalStr, str1));
console.log(replacing(originalStr, str2));
console.log(replacing(originalStr, str3));
console.log(replacing(originalStr, str4));
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
function replaceFromEnd(string1, string2){
return string1.substr(0, string1.length - string2.length) + string2;
}
console.log(replaceFromEnd(originalStr, str1));
console.log(replaceFromEnd(originalStr, str2));
console.log(replaceFromEnd(originalStr, str3));
console.log(replaceFromEnd(originalStr, str4));
Related
I can change the last part (in the URL: child) of the URL, but if the URL's parameters exist, these parameters are deleted by this change (?para=1¶=2).
Is there a way to not delete the parameters?
Sample:
https://example.com/sub/child?para=1¶=2
JS:
const str = window.location.href;
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path + "/new_child";
window.history.pushState("object or string", "Title", new_path);
window.history.replaceState("object or string", "Title", new_path);
Before replacing the last part you can save the parameters like this
var str = "https://example.com/sub/child?para=1¶=2";
var params = str.split('?')[1]
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path + "/new_child?"+params;
console.log(new_path)
Alternatively you can create a function to do this using regex
var str = "https://example.com/sub/child?para=1¶=2";
const new_path = replaceUrlPart(str, "child", "new_child")
console.log(new_path)
function replaceUrlPart(url, partToRemove, partToAdd){
return url.replace(partToRemove,partToAdd);
}
I am trying to create a folder using javascript but before I do that I need to check if the folder exists and if it does increase the number by 1.
Here's my input name: The ABC Group
I want javascript to remove ‘The’ and move it to the end and then finally add a code based on the first 4 characters followed by a number. If the first 4 characters don’t exist in the directory then it will start 01 and increment from there on.
Here's what I want to output:
I.e. ABC Group, The (ABCG01)
I am new to javascript but I have so far worked out how to do everything apart from the number part which I am stuck on.
Here's my code:
var clientName = "the ABC company";
// Change Case - START
const toCapitaliseCase = (phrase) => {
return phrase
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let capitalise = toCapitaliseCase(clientName);
// Change Case - END
// Format Client Name if starts with 'The' - START)
if (capitalise.startsWith('The ')) {
let words = capitalise.split(' ');
let the = words[0];
let theSlice = capitalise.slice(4);
let comma = ', ';
let name = theSlice.concat('', comma, the);
let name2 = name.replace(/[^0-9a-zA-Z]/g, "");
let theSlice2 = name2.slice(0,4);
var upper = theSlice2.toUpperCase(); // output - "i am a crazy string, make me normal!"
let numbecccr = '101';
let theSlice3 = numbecccr.slice(1);
let FullCompiledName = theSlice.concat('', comma, the, ' (',upper, theSlice3, ')');
console.log(FullCompiledName);
// Format Client Name - START
}
I put your code into a function, in which I counted the number up each time the function gets called.
var clientName = "the ABC company";
function createName(clientName) {
this.number = this.number || 0;
// Change Case - START
const toCapitaliseCase = (phrase) => {
return phrase
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let capitalise = toCapitaliseCase(clientName);
// Change Case - END
// Format Client Name if starts with 'The' - START)
if (capitalise.startsWith('The ')) {
let words = capitalise.split(' ');
let the = words[0];
let theSlice = capitalise.slice(4);
let comma = ', ';
let name = theSlice.concat('', comma, the);
let name2 = name.replace(/[^0-9a-zA-Z]/g, "");
let theSlice2 = name2.slice(0,4);
var upper = theSlice2.toUpperCase(); // output - "i am a crazy string, make me normal!"
this.number++;
let num = this.number;
if(('' + num).length == 1) {
num = '0' + num;
}
let FullCompiledName = theSlice.concat('', comma, the, ' (',upper, num, ')');
return FullCompiledName;
}
}
console.log(createName(clientName));
console.log(createName(clientName));
I have a code that simply compares str2 (User input) with str1 (our reference string ) to check if any word in str2 is typed wrongly or correctly. The code works fine but I can't find a solution to this problem:
I want to ignore extra spaces, commas and dots and any other writing signs to be compared in both strings. just like a dictation app...
for example, below strings should assume as equal strings on output:
str1 = "I was sent to earth"
str2 = "I was, sent to: earth."
Any other modifications to improve this code is extremely appreciated.
Please Help...
var str1 = "I was sent to earth to protect my cousin";
var str2 = "I waz Sent to earth to protet my cousine";
let a = str1.toLowerCase().split(' ');
let b = str2.toLowerCase().split(' ');
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
console.log(res1);
console.log(res2);
var str1 = res1.toString();
str1 = str1.replace(/,/g, '\n');
var str2 = res2.toString();
str2 = str2.replace(/,/g, '\n');
var player = GetPlayer();
player.SetVar("wrong_Spell",str1);
player.SetVar("right_Spell",str2);
You could use match to extract the words using \w+:
function words(s) {
return s.toLowerCase().match(/\w+/g);
}
var str1 = "I was sent to earth to protect my cousin";
var str2 = "I waz Sent to earth to protet my cousine";
let a = words(str1);
let b = words(str2);
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
console.log(res1);
console.log(res2);
How to remove duplicate from string for example
const string = 'PandoraPandora'; to --> Pandora
OR
const string = 'pandorapandora'; to --> pandora
Note: string doesn't have spaces.
Here you go:
const str = 'pandorapandora'
const midIndex = Math.floor(str.length/2)
const firstHalf = str.slice(0,midIndex)
const secondHalf = str.slice(midIndex)
const dup = firstHalf == secondHalf ? firstHalf : str
console.log(dup)
I have a string var with following:
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
Note that the value is separated by , respectively, and the val is not fixed / hardcoded.
How do I replace only the bVal everytime?
EDIT
If you use string as the regex, escape the string to prevent malicious attacks:
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
new RegExp(RegExp.escape(string));
var str = "aVal,bVal,cVal,dVal,eVal";
var rgx = 'bVal';
var x = 'replacement';
var res = str.replace(rgx, x);
console.log(res);
Try this
var targetValue = 'bVal';
var replaceValue = 'yourValue';
str = str.replace(targetValue , replaceValue);