How to delete duplicate from string - javascript

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)

Related

How to find all the matches?

This code helps me find text between start&end words. But the search ends after the first pair found. How to find all the matches?
const file = fs.readFileSync('./history.txt', 'utf8')
const startString = '-----CompilerOutput:-stderr----------'
const endString = '-----EndCompilerOutput---------------'
const startIndex = file.indexOf(startString) + startString.length
const endIndex = file.indexOf(endString)
const between = file.slice(startIndex, endIndex)
console.log(between)
Use
const startIndex = file.match(/-----CompilerOutput:-stderr----------/gi)
const endIndex = file.match(/-----EndCompilerOutput---------------/gi)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://www.w3schools.com/jsref/jsref_match.asp

Replace string from last without changing string length

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));

How do I replace same character occurrence with different characters

I have a string like:
my_str = "select * from users where id = ? and name = ?;"
I also have an array to replace '?'
var arr = [1,'test']
I wanted to replace first ? with 1 and second ? with 'test' in
jQuery/JavaScript dynamically. There can be a number of ? in string.
Note this question has no relation with MySQL the query I have written is just a string.
For a more dynamic option, where replace is an array containing the replacements in order:
const string = 'select * from users where id = ? and name = ?;'
const replace = [1, 'test']
let index = 0
const output = string.replace(/\?/g, () => replace[index++])
console.log(output)
use replace method multiple times for replacing.
var my_str = "select * from users where id = ? and name = ?;"
my_str = my_str.replace("?","1"); //replaces first "?"
my_str = my_str.replace("?","test"); //replaces second "?"
alert(my_str);
Using the replace function you can do that, just use replace multiple times to replace both '?'.
var my_str = "select * from users where id = ? and name = ?;"
var arr = [1,'test']
my_str = my_str.replace("?",arr[0]).replace("?",arr[1]);
console.log(my_str);
use replace() multiple times
var r = "select * from users where id = ? and name = ?;".replace("?", '1').replace('?','test');
console.log(r);
and if you have an array of values to replace the '?':
var arr = [1,'test']
var r = "select * from users where id = ? and name = ?;"
for(i=0; i<arr.length; i++){
r = r.replace('?',arr[i]);
}
console.log(r);
Get index of ? and put into a array, then write a function to replace.
var str = "select * from users where id = ? and name = ?;"
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "?") indices.push(i);
}
str = replaceAt(str,0,"1");
str = replaceAt(str,1,"Jonh");
alert(str);
function replaceAt(str, index, replacement) {
return str.substr(0, indices[index]) + replacement+ str.substr(indices[index] + 1, str.length);
}
https://jsfiddle.net/vuph31/hgbms2s1/1/

Separate string into multiple variables with JavaScript

Using JavaScript I want to take a string like this var hashStr = 'modal-123456' and assign the string left of the - to a variable and the string right of the - to another variable.
If the string does not contain a - then ignore it.
How can I best achieve this?
var hashStr = location.hash.replace('#', '');
// hashStr now === 'modal-123456'
var firstHalf = // modal
var secondHalf = // '123456'
You can use split API.
var hashStr = 'modal-123456'
var splitStr = hashStr.split('-');
console.log(splitStr[0])
console.log(splitStr[1])
Just use split.
var hashStr = 'modal-123456';
var [firstHalf, secondHalf] = hashStr.split("-");
console.log("first half:", firstHalf);
console.log("second half:", secondHalf);
Simply
var hashStr = location.hash.replace('#', '');
var firstHalf = hashStr.split("-")[0];
var secondHalf = hashStr.split("-")[1];
or
var hashStr = location.hash.replace('#', '').split("-");
var firstHalf = hashStr[0];
var secondHalf = hashStr[1];

Problems with cross-language HMAC / SHA256 / Base64

I'm using a node.js script to create a signature for azure documentDB - the simplified version is (result at the bottom):-
var crypto = require("crypto");
var masterKey = "ABCDE"
var key = new Buffer(masterKey, "base64");
var signature = crypto.createHmac("sha256", key).update("FGHIJ").digest("base64");
console.log("\n\n"+signature)
// RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo=
This works, and does what I need it to. I'm trying to do the same thing in Swift with CommonCrypto
let keyString = "ABCDE"
let body = "FGHIJ"
let utf8data = keyString.dataUsingEncoding(NSUTF8StringEncoding)
let key = utf8data!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let str = body.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = body.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key.bytes, key.length, str!, strLen, result);
var hmacData = NSData(bytes: result, length: digestLen)
var hmacBase64 = hmacData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
result.dealloc(digestLen)
let signature = String(hmacBase64)
let test = "RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo="
XCTAssert(test == signature, "Pass")
But it returns a completely different result. If I pass the masterKey directly into the javascript hmac, and pass it in as a string into the CCHmac method in Swift, it all works; so it seems to be something to do with finding the equivalent to this:-
var key = new Buffer(masterKey, "base64");
Thoughts?
More information - this:-
let keyString = "ABCDE"
let body = "FGHIJ"
let keyData = keyString.dataUsingEncoding(NSUTF8StringEncoding)! // .base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let bodyData = body.dataUsingEncoding(NSUTF8StringEncoding)!
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyData.bytes, keyData.length, bodyData.bytes, bodyData.length, result);
var hmacData = NSData(bytes: result, length: digestLen)
var hmacBase64 = hmacData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
result.dealloc(digestLen)
let signature = String(hmacBase64)
let test = "FA372zbobgpTLI5cQWh5YFiFwkNhMI8womX4Cvw68YE=" // "RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo="
XCTAssert(test == signature, "Pass")
Produces the same result as this:-
var crypto = require("crypto");
var masterKey = "ABCDE"
var signature = crypto.createHmac("sha256", masterKey).update("FGHIJ").digest("base64");
console.log("\n\n"+signature)
// FA372zbobgpTLI5cQWh5YFiFwkNhMI8womX4Cvw68YE=

Categories