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

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

Related

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

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.

How to check if a string meets required format using regex in javascript? [duplicate]

This question already has answers here:
Regex pattern accepting comma separated values
(5 answers)
Closed 4 years ago.
I want to check if a given string meets the required format in javascript. I want to use regex to do it, but I can not write the proper regex.
The required format is like optiona;optionb;optionc, and there will be
at least one ; in the string to separate the option, each option will
have at least three characters.
The options value can not contain ; but can contain empty space inside it (not in the beginning or end)
below is some example of it:
var str1="aaa;BBC;ccc";//valid
var str2=";aaa;bbb;ccc";//invalid, because it starts with ;
var str3="aaa;bbb;ccc;";//invalid, because it ends with ;
var str4="aaa;bbb;ccc;ddd"; //valid
var str5="aaa;b;ccc";//invalid, because the second option is b, the length is less than 3
var str5="aaa;bbb;;ccc";//invalid, because it has duplicate ;
var str6="aa a;bbb;ccc";//valid
var str7="aaa ;bbb;ccc";//invalid,empty space in the end of first option
var str8=" aaa;bbb;ccc";//invalid,empty space in the begin the first option
var str9="aaa;bb b;ccc;ddd";//valid
var str10="aaa;bbb ;ccc;ddd";//invalid,empty space in the end of second option
var11="aaa;bbb";//valid
How to use regex to check it. Can anyone help me? Thanks in advance!
The only tricky part to this problem is checking length while following other rules. So an option with 3 characters long would be matched with:
\w[ \w]+\w
Here is the regex:
^\w[ \w]+\w(;\w[ \w]+\w)+$
^^^^^^^^^^ ^^^^^^^^^^
Beginning and end of input string anchors, ^ and $, should be used. I used a capturing group construct but you may want to change it to a non-capturing one.
Live demo

Regex Only one special character at a time from allowed special characters 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 4 years ago.
Improve this question
I want to allow 3 characters 1st Underscore (_) , 2nd hyphen (-) 3rd Dot (.)
but i want to put conditions that only one character is allowed at a time from all of them, and also only one time.
e.g
allowed usernames = abc.def , abc-def , abc_def
not allowed usernames = abc.de.f alert here(only one special character is allowed in a username)
not allowed usernames = abc.de-f , abc.de_f , ab-cd_ef
What should i do.
Try /^[a-z]*[-._]?[a-z]*$/
var tests = ['abc.def', 'abc-def', 'abc_def', 'abc.de.f','abc.de-f' , 'abc.de_f', 'ab-cd_ef'];
$.each(tests, function(a,b) {
$('body').append('<div>' + b + ' = ' + regIt(b) + '</div>');
});
function regIt(str) {
return /^[a-z]*[-._]?[a-z]*$/.test(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
^[a-z]*([-._]?)(?:[a-z]|\1)*$
This regex will match letters until it reaches the end of the string. If it reaches a symbol (- . or _) it will store that symbol as group 1, and keep matching for letters or that same symbol until the end of the string.
The following are matching examples:
an empty string
_something
something-something
foo_bar_baz
foo.
And here are some invalid strings:
my_file.txt
alpha.bravo_charlie
not-working_

Categories