masking a string with # [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Hi can someone please look over my code and tell me what i have to fix. The function of this code is that it takes any given string in the argument and hides the characters of the string with a #. All the characters are hidden except the last 4. I dont know why I am not getting the desired output. Please feel free to run the code and see. I would prefer the solutions to be corrections or improvements to my code and not new pieces of code. Thank you!
const maskify = (info) => {
let fourSaved = info.slice((info.substr(-4))) // put a negative number within the parameters so it starts from backwards. This variable will save the last 4 characters of the string.
const infoArr = info.split(", ") //turned string into an array for easier manipulation
for(let i = 0; i < infoArr.length; i++){
infoArr[i] = "#" //so each and every element in the array is changed into a #
console.log(infoArr.join(''));
}
let arrStr = infoArr.join(''); //Changing array back to string
let masked = arrStr.replace(arrStr.substr(-4), fourSaved); // putting the last 4 characters of the string back into it.
return masked
}
console.log(maskify("hello world")) //desired output should be: ##### #orld

Here is the answer:
const maskify = (info) => {
return info.slice(0, -4).replace(/[a-zA-Z]/g, '#').concat(info.slice(-4, info.len));
}
console.log(maskify("hello world")) //desired output should be: ##### #orld
Explanation:
First, I slice the string until the last four letters.
Then, replace all the characters in the returned string with pound character.
This is done by using Javascript Regular Expression, this specific one replaces all of the letters in the string (between a-z and A-Z).
After that, concat that string with the last 4 characters of the original string.
Finally, the result is returned.
For more info on Regex:
MDN regex
Example
Your Code, Changed:
If you purposefully want to use the loop way, here is your code changed so it returns the correct result:
const maskify = (info) => {
let fourSaved = info.slice(-4) // put a negative number within the parameters so it starts from backwards. This variable will save the last 4 characters of the string.
const infoArr = info.split(", ") //turned string into an array for easier manipulation
for(let i = 0; i < infoArr.length; i++){
infoArr[i] =infoArr[i].replace(/[a-zA-Z]/g, '#') //so each and every element in the array is changed into a #
}
let arrStr = infoArr.join(''); //Changing array back to string
let masked = arrStr.slice(0, -4) + fourSaved;
return masked
}
console.log(maskify("hello world")) //desired output should be: ##### #orld

Related

How to get the part of the string after the 2nd space [duplicate]

This question already has answers here:
Cutting a string at nth occurrence of a character
(5 answers)
Closed 1 year ago.
I am having a string like: $m-set 88829828277 very good he is. From this string I want to get the part after the second space. ie, I want to get: very good he is.
I tried using split(" ")[2] but it only gives one word: very.
Any help is greatly appreciated!
Thanks!
While you could split and join:
const input = '$m-set 88829828277 very good he is';
const splits = input.split(' ');
const output = splits.slice(2).join(' ');
console.log(output);
You could also use a regular expression:
const input = '$m-set 88829828277 very good he is';
const output = input.match(/\S+ \S+ (.+)/)[1];
console.log(output);
where the (.+) puts everything after the second space in a capture group, and the [1] accesses the capture group from the match.

Find and replace # mentions using Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])

Remove sub-string from URL containing only numbers [duplicate]

This question already has answers here:
How to remove numbers from a string?
(8 answers)
Closed 3 years ago.
I have a few URL's like these
https://{Domain}/rent/abcdef/2019/Canada
https:/{Domain}/buy/Supported/2019/Gill-Avenue
I want to remove '2019'or any part which contain only numbers from these Url's so that the Url's look as below
https://{Domain}/rent/abcdef/Canada
https:/{Domain}/buy/Supported/Gill-Avenue
How can i achieve this using javascript
You can try this;
let str = "https://test.com/rent/abcdef/2019/Canada";
str.replace(/\/\d+/g, '');
You should try something like that:
split on '/', filter with a /d regex and rejoin with '/'
I can't try right now sorry
window.location.href.split('/').filter(substr => !(/^\d+$/.match(substr))).join('/')
Try to do this for the first:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("f//", "f/");
And for the second:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("d//", "d/");
So this is if you want to replace just 1 digit. The first one of each of these works but adds a new / backslash to the whole link after the last letter before the / in the old version. To remove that, you do the second, which contains the last letter to not remove the :// too. The way is to find the last letter of each of these numbers before the backslash after using the first replace() function and replace them to remove the extra backslash.
This might work for easy things, like if you already know the URL, but for complicated things like a very big project, this is no easy way to do it. If you want "easy", then check other answers.
As said, you can also do this:
let str = "https://test.com/rent/abcdef/2019/Canada";
var withNoNum = str.replace(/\/\d+/g, '');
This is going to remove groups of numbers. So I added a new string withNoNum which is str's replacement with no numbers, which might be more good because if you are doing a website that allows you to send your own website and remove the numbers from it to get a new site.
This also might help you with this problem: removing numbers from string

how to only end breket in double breket regexp match [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
const input = "sample(1)(2)sample(3)sample(4)(5)sample(6)(7)sample(8)sample(9)"
const regexp = new RegExp(????) // <-- what i want
input.match(regexp)
result: [sample(1)(2), sample(3), sample(4)(5), sample(6)(7), sample(8), sample(9)]
how to match only end of breket???
This should do what you want:
input.match(/(.*?\))(?=($|[^(]+))/g)
(updated to also match at end of input)
I'll explain my answer in details , but first i'll post the code:
var input = "sample(1)(2)sample(3)sample(4)(5)sample(6)(7)sample(8)sample(9)";
var regex = /\)\w/;
var words = [];
while (input.search(regex) !== -1) {
words.push(input.slice(0, input.search(regex) + 1));
input = input.slice(input.search(regex) + 1, input.length); //start slicing right after the ")" until the end
}
words.push(input);
console.log(words);
The regex variable contains a regular expression that will match any ) followed by a word character.
The words array contains separated words.
The search() method accept a string or a regular expression as a parameter , if there's a match , the index where this match occurred is returned , otherwise (if there's no match) -1 is returned.
The slice(startIndex, endIndex) method accepts two parameters , a start index , and an end index , it does return a part of the string starting from startIndex and ends at endIndex - 1.
At first , the search method will match sample(1)(2) ,so sample(1)(2) is pushed into the array and the input now consist of: sample(3)sample(4)(5)sample(6)(7)sample(8)sample(9)
Once again , the search method will match sample(3) ,so sample(3) is pushed into the array and the input now consist of: sample(4)(5)sample(6)(7)sample(8)sample(9)
Once again , the search method will match sample(4)(5) ,so sample(4)(5) is pushed into the array and the input now consist of: sample(6)(7)sample(8)sample(9)
Once again , the search method will match sample(6)(7) ,so sample(6)(7) is pushed into the array and the input now consist of: sample(8)sample(9)
Once again , the search method will match sample(8) ,so sample(8) is pushed into the array and the input now consist of: sample(9)
Now , the search method doesn't match the regular expression in sample(9) , because there's only ) at the end , and no word character comes after it , that's why i'm pushing it manually at words.push(input);
You can read more about these methods in the following links:
slice(): http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
search(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search

Match string entries by regexp and create splitted array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a string:
const str = 'my string is awesome <%010203%> and super cool <%090807%>'
Where symbols in the <%%> is ids.
I have a function that gets some data by that id getDataById(id). I want to create an array from this string that should look like this:
const arr = ['my string is awesome ', getDataById('010203'), ' and super cool ', getDataById('090807')]
How can i do it? Thank you
Since I do not know what you have tried I can't help with your understanding of where you might have found difficulty with this.
So, starting from zero it appears you would need to split the string into parts and replace the value for only the parts that match the ID format with a function call. Luckily, the split occurs where the replacement also occurs.
Solving the first part, we can use split with a regex as a separator and also using a capture to include the ID part in the output.
str.split(/<%(\d+)%>/)
If we did not include the capture for the ID, the separator would not be included in the output.
Now for the conversation of the ID to a function call. map is perfect for iterating over an array (the output of split) and converting it to a new array with a transformation for each element. However since we only want to replace the IDs with the function call we won't need to transform every value. This means we will need to test when to or not to transform a value.
For the testing, a simple approach could be to use another regex to see if the value is an ID format but, however odd, it could be possible to have a false-positive match of a non-ID string.
Another approach is that since the output of the split is an array like:
['some string', ID, 'some other string', ID, 'this could look like an ID', ID, ...]
then we can quickly see that the ID is every other element of the array. Using a remainder (or modulo) on the index value of the iteration then would allow us to quickly and with certainty know that we have an ID.
arr.map((val, index) => index % 2 ? getDataById(val) : val)
const str = 'my string is awesome <%010203%> and super cool <%090807%>';
const arr = str
.split(/<%(\d+)%>/)
.map((v, i) => i % 2 ? `getDataById('${v}')` : v); // outputting with template to show desired value
console.log(arr);
While adding everything to an array like that is slightly awkward simply replacing the values in the string would be easier. If that would work for you then here is a simple implementation of that.
const str = 'my string is awesome <%010203%> and super cool <%090807%>';
function getDataById(id) {
return '(My data: ' + id + ')';
}
console.log(str.replace(/<%(\d+)%>/g, getDataById('$1')));
We're matching any of the tags by matching <% followed by a capture case of 1 or more digits followed by a %>. We are then replacing that with our getDataById() function and passing in the value of our capture case.

Categories