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

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.

Related

Restore a string that has randomly inserted characters [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 1 year ago.
Improve this question
I would like to clean this string How52363262362366are9you?, or any similar string that the user inputs, using wherever character he wants.
This was my first approach :
function buildstring(str){
var reg =/[0-9]/g;
let newStr = str.replace(reg, '');
return newStr;
}
console.log(buildstring('How52363262362366are9you?'));
This way I'm only deleting the digits. I can make the regex even better by adding some non alphanumeric characters, but let's keep it simple.
This function returns Howareyou?. Now I want to separate the words with a space to reconstruct the sentence.
My first idea was using split(''), but of course didn't work...
How to solve this? Is there any way to make that a word starts at point a and ends in point c?
Just change your regex a bit so that it matches grouped numerical characters, and replace each group with a space.
function buildstring(str){
var reg =/[0-9]+/g;
let newStr = str.replace(reg, ' ')
return newStr
}
buildstring('How52363262362366are9you?')
there are several approaches.
You could consider it a case for Functional Programming (since there's a flow of transformations).
Something like this:
function buildstring(str){
return str
.split('')
.filter((character) => !'0123456789'.includes(character))
.join('');
}
console.log(buildstring('How52363262362366are9you?'));
If you use split(' ') (or even break on \s to consider tabs and newlines), you'll have „words” (with interpunction).
By breaking up the code into smaller functions, you can compose them.
For example, the .filter() could be a stripnumerals function.
This way, you can compose the transformations as you please.

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

masking a string with # [closed]

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

How to filter a string data? [duplicate]

This question already has answers here:
Filter array by string length in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I have a string for example:-
String: Notification 'Arcosa-Incident assigned to my group' 8ff7afc6db05eb80bfc706e2ca96191f included recipients as manager of a group in the notification's "Groups" field: 'Ruchika Jain' 9efa38ba0ff1310031a1e388b1050e3f
So basically i convert it into an array using .split(' ') method to make it comma separated values, now i want to filter this array and want only values which are 32 character long and remove rest of values.
Please help me achieve this. Alternate solutions are also welcomed. Thanks in advance.
Assuming you want to grab those IDs you can simply use a regex with match on the string without splitting/filtering it. (Note: I had to escape the single quotes in the text.)
const str = 'String: Notification \'Arcosa-Incident assigned to my group\' 8ff7afc6db05eb80bfc706e2ca96191f included recipients as manager of a group in the notification\'s "Groups" field: \'Ruchika Jain\' 9efa38ba0ff1310031a1e388b1050e3f';
const matches = str.match(/[a-f0-9]{32}/g);
console.log(matches);
Like so:
var arr = ...;
var filtered = arr.filter(word => word.length === 32);
Edit: this may be a bad idea if you want to parse only the GUIDs. It could certainly be that a name like "Ruchika" is also 32 characters long. Maybe, consider using regular expressions instead.

RegEx: Extract GET variable from URL [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.

Categories