Replace substring with its exact length of another character - javascript

I am trying to replace a substring within a string with an exact number of other characters.
Example:
Input: Hello There, General Kenobie!
Output: xxxxx There, xxxxxxx Kenobie!
I can get this to work if I replace it with a preset string:
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
console.log(text.replace(pattern, "xxx"));
Output: xxx There, xxx Kenobie!
What am I missing wrapping my head around.
Thanks!

You are using a hard-coded string of 'xxx' as your replacement string. So, that's what you are seeing... the string(s) replaced with 'xxx'.
The .replace() method actually supports a function as the replacement, instead of a string, so that's what you need here.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
const newText = text.replace(pattern, (str, m) => 'x'.repeat(m.length));
console.log(newText);

You can always loop through the matches and replace each separately.
let text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
let array1;
while ((array1 = pattern.exec(text)) !== null) {
wrap = array1[0][0];
text = text.replace(array1[0],wrap + "x".repeat(array1[0].length-2) + wrap);
}
console.log(text)

Related

Remove a substring to make given word in javascript

I want to know about the algorithm for below question in JavaScript.
Check whether the given word can be "programming" or not by removing the substring between them. You can only remove one substring from the given the word.
Give answer in 'yes' and 'no'
example answer explanation
"progabcramming" yes remove substring 'abc'
"programmmeding" yes remove substring 'med'
"proasdgrammiedg" no u have to remove 2 subtring 'asd' and 'ied'
which is not allowed
"pxrogramming" yes remove substring 'x'
"pxrogramminyg" no u have to remove 2 subtring 'x' and 'y'
which is not allowed
Please tell me an algorithm to solve it
{
// will create a regexp for fuzzy search
const factory = (str) => new RegExp(str.split('').join('(.*?)'), 'i')
const re = factory('test') // re = /t(.*?)e(.*?)s(.*?)t/i
const matches = re.exec('te-abc-st') ?? [] // an array of captured groups
const result = matches
.slice(1) // first element is a full match, we don't need it
.filter(group => group.length) // we're also not interested in empty matches
// now result contains a list of captured groups
// in this particular example a single '-abc-'
}
I'm not sure how efficient this code is, but only thing i can come up with is using regular expression.
const word = 'programming';
const test = ['progabcramming', 'programmmeding', 'proasdgrammiedg', 'pxrogramming', 'pxrogramminyg', 'programming'];
// create regular expression manually
// const regexp = /^(p).+(rogramming)|(pr).+(ogramming)|(pro).+(gramming)|(prog).+(ramming)|(progr).+(amming)|(progra).+(mming)|(program).+(ming)|(programm).+(ing)|(programmi).+(ng)|(programmin).+(g)$/;
// create regular expression programmatically
let text = '/^';
word.split('').forEach((character, i) => {
text += i ? `(${word.substring(0, i)}).+(${word.substring(i)})|` : '';
});
text = text.substring(text.length - 1, 1) + '$/';
const regexp = new RegExp(text);
// content output
let content = '';
test.forEach(element => {
content += `${element}: ${regexp.test(element)}\n`;
});
document.body.innerText = content;

How to remove part of string that is in parentheses?

I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?
Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);
You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo
const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());

Regex to extract text from a string

Given the following string:
const myString = "This is my comment content. [~firstName.lastName]";
What is a javascript regex to extract the "firstName" and "lastName"?
What is a javascript regex to extract the content minus the "[~firstName.lastName]"?
I'm rubbish with Regex.
const myString = "This is my comment content. [~firstName.lastName]";
const first = myString.match(/.*\~(.*)\./)[1]
const last = myString.match(/.*\.(.*)]/)[1]
const both = myString.match(/.*\~(.*)\]/)[1]
console.log(first)
console.log(last)
console.log(both)
Here's a good website for regex help
You can try this-
let myString = "This is my comment content. [~firstName.lastName] and the original name is [~John.Doe]";
const regex = /\[~([^\]]+)\.([^\]]+)\]/g;
let match = regex.exec(myString);
const names = [];
while(match !== null) {
names.push({firstName: match[1], lastName: match[2]});
match = regex.exec(myString);
}
// Remove the pattern from the original string.
myString = myString.replace(regex, '');
console.log(names, myString);
This code will find all the matches found for the pattern.
You could target each name separately. match will return the complete match as the first element of the array, and the groupings specified by the ( and ) in the regex as the subsequent elements.
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\.(.+)\]/;
console.log(str.match(regex));
Or you could target just the characters within the brackets and then split on the ..
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\]/;
console.log(str.match(regex)[1].split('.'));

Extending a regex to capture multiple conditions

Currently have the following regex to capture all content within square brackets:
regex = /[^[\]]+(?=])/g
Meaning that:
string = "[Foo: Bar] [Biz: Baz]"
string.match(regex)
In JavaScript will return: ["Foo: Bar", "Biz: Baz"]
for a next step, I want to only get the text that follows a the colon. It is safe to assume that on all matches, we'll consistently have a return where each string in the return array matches the above pattern.
I'm sure there's some way to extend my regex to do this at the same time as finding the text within square brackets, but I'm just not sure how to do so. I've tried using some positive look-aheads, but I have no idea where to add them.
Another simple way:
const regex = /\[(\w+)\s*:\s*(\w+)\]/g;
const string = "[Foo: Bar] [Biz: Baz]";
let match;
while(match = regex.exec(string)){
console.log(`Pro: ${match[1]}`)
console.log(`Val: ${match[2]}`)
}
You can add :) or (: ) if you need also to match the space after the colon):
var string = "[Foo: Bar] [Biz: Baz]"
var regex = /[^[\]:]+(?=])/g;
console.log(string.match(regex));
You can try something like this
\[([^:]+:\s*)([^\]]+)
let regex = /\[([^:]+:\s*)([^\]]+)\]/g
let arr = []
let string = "[Foo: Bar] [Biz: Baz]"
while((arr =regex.exec(string))!== null){
console.log(`key -> ${arr[1]}`)
console.log(`val -> ${arr[2]}`)
}

Creating a regex to replace each matched character of a string with same character

In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).
For example
Input: HGHG8686HGHG8686H
Output: XXXXXXXXXXXXX686H
The Regex I wrote to perform the replace on the string is as follows
[a-zA-Z0-9].{12}
Code:
const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?
you can use a function inside replace to do this, something like this will do:
var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);
The simple version: (Easier to read)
const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1
Now using: [a-zA-Z0-9]
const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1
Note: The reason i match on the START PLUS TWO characters is to offset the first match. (The final 4 characters that are appended at the end.)
Look ahead (?=) to make sure there are at least four following characters.
const regex = /.(?=....)/g;
// ^ MATCH ANYTHING
// ^^^^^^^^ THAT IS FOLLOWED BY FOUR CHARS
function fix(str) { return str.replace(regex, 'X'); }
const test = "HGHG8686HGHG8686H";
// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();
<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>
A non-regexp solution:
const test = "HGHG8686HGHG8686H";
function fix(str) {
return 'X'.repeat(str.length - 4) + str.slice(-4);
}
console.log(fix(test));
You will not find String#repeat in IE.
You can achieve using following method:
var str = "HGHG8686HGHG8686H"
var replaced=''
var match = str.match(/.+/)
for(i=0;i<match[0].length-4;i++){
str = match[0][i]
replaced += "X"
}
replaced += match[0].substr(match[0].length-4)
console.log(replaced);

Categories