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])
Related
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.
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
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a string that represents a fraction and I want to extract the numerator and denominator.
var stringFraction = '99/99 (100%)';
var fraction = stringFraction.split(' ')[0].split('/');
console.log(0, Number(fraction[0]));
console.log(1, Number(fraction[1]));
This works fine but I'm wondering if a regex would be better?
Using a regex, you would be able to go for a simple match/find.
In your case, you first split the fraction itself from the remaining part, to then split again on the '/'.
In other words: a regex would allow you to reduce your code to a single match operation.
See here for some guidance how that would work.
Of course, you could also do that specific "matching" in a more manual mode:
get the string from 0 to index-1 of '/'
get the string from '/' to ' '
In other words, there are plenty of ways to retrieve that information. Each one has different pros and cons, and the real answer for a newbie learning this stuff: make experiments, and try them all.
There is no reason you can't do trimming and all with a single regex
without having to go through the gyrations with split.
Try this
/0*(\d+)\s*\/\s*0*(\d+)/
Formatted
0*
( \d+ ) # (1)
\s* / \s*
0*
( \d+ ) # (2)
JS sample
var strSample =
"0039/99 (100%)\n" +
"00/000 (100%)\n" +
"junk 102 / 487\n";
var NumerDenomRx = new RegExp( "0*(\\d+)\\s*/\\s*0*(\\d+)", "g");
var match;
while ( match=NumerDenomRx.exec( strSample ))
{
console.log("numerator = ", match[1] );
console.log("denominator = ", match[2] );
console.log( "-------------------------" );
}
If all strings have the same pattern
var stringFraction = '99/99 (100%)';
var fraction = stringFraction.match(/\d+/g); // result = ["99", "99", "100"];
Now technically this is shorter than spliting it, 15 vs 26 letters/signs/spaces, but only if the length of the array doesn't bother you. Otherwise you will have to chain extra method
.slice(1,-1)
that's +12 extra signs/letters. If the string is more complex
var fraction = stringFraction.match(/\d+\/\d+/)[0].split('/');
There are endless variations how to solve it really
P.S. Unless you got more complex strings, regex is not needed.
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.
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 7 years ago.
Improve this question
How do I find and extract capitalized words of a string with regex?
I would like to:
extract the capitalized words of a string, as an array
extract the last capitalized word of a string, as a substring:
Both with one regex
If I have this:
var str="This is a STRING of WORDS to search";
I would like to get this 1:
allCapWords // = ["STRING", "WORDS"]
and 2:
lastCapWord // = "WORDS"
To extract the words into an array:
var allCapWords = str.match(/\b[A-Z]+\b/g);
-> ["STRING", "WORDS"]
(Here's a Regex101 test with your string.)
To pull the last word:
var lastCapWord = allCapWords[allCapWords.length - 1];
-> "WORDS"
var str="This is a STRING of WORDS to search";
var regObj = /\b([A-Z]+)\b/g;
allCapWords = str.match(regObj);
You can try this regexpr /\b[A-Z]+\b/gor \b[A-Z0-9]+\b/g if you are interested in catch numbers inside the string