Restore a string that has randomly inserted characters [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 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.

Related

Replace string pattern but keep part of it [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 5 months ago.
Improve this question
I have a long document with some headings I want to replace in a operation.
The headings have the following structure (there are two nouns, both in with a uppercase first character, separated with a whitespace, also the time is dynamic):
let string = 'Firstname Lastname [00:01:02]';
I want to insert some characters at the front and the end of this string, but want to keep the content.
So the desired output should be something like:
let string = '{Firstname Lastname [00:01:02]}:';
I tried a little bit around with RegEx and can catch the time with the following pattern:
\[[0-9]{2}:[0-9]{2}:[0-9]{2}
I figured it out by using captures in my RegEx.
/(\b[A-Z][a-z]* [A-Z][a-z]*( [A-Z])?\b\s\[[0-9]{2}:[0-9]{2}:[0-9]{2}\])/g
This RegEx captures the pattern of my headings into group one. In a replace operation I can then insert the desired content.
string.replace(regex, '{$1}:')

Why regex doesn't work some times 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 2 years ago.
Improve this question
Hello I'm using regex to validate inputs, The idea is that the user cannot type some characters based on regex. I tested with 2 regex, but te first doesn't work.
Even I test on that page: https://regexr.com/
and both works fine, but in the code they don't.
Would you please helpme? Thanks.
I need a regex that letme type range betwen 0 and 180
the desired behaviour:
function regex1(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/g.test(val);
});
return filterArray;
}
function regex2(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/[^1-3]+/g.test(val);
});
return filterArray;
}
console.log(regex1("180"));
console.log(regex2("3"));
Your problem lies on two fronts:
Your var splitStr = str.split(""); line is splitting the string down to individual characters, which means you are never testing '180', but '1', '8', and '0' separately
RegEx is a poor tool to validate numerical range
You should really really really reconsider using regex for this purpose, and instead should parse the input into a number and test it, unless there's some other reason that you need to do it this way. One reason to parse and test instead is that there may be edge cases that your expression doesn't cover, even though they may be valid.
If, for some reason, you absolutely must use regex, you need to test the string(s?) as a whole, rather than char by char, just by using the same RegExp.prototype.test() function like you already were:
function regex1(str) {
return /^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/g.test(str);
}
var tests = ['0', '1', '120', '180', '181'];
for (var str of tests)
console.log(`${str}:`, regex1(str));
As an example of an alternate solution:
If you're using HTML <input>s for form input, then they already have a mechanism for setting a max (and min) numerical input. Trying to submit with invalid input will prevent form submission:
<form>
<input type="number" max="180" placeholder="0 - 180">
<input type="Submit">
</form>

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

String fraction to numbers [closed]

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.

using regex in javascript to check if foreign characters [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 5 years ago.
Improve this question
I'm trying to create a simple function that checks if there are foreign characters in my string. Essentially, this is what I'm trying to get:
var str_1 = "отправка.py" // should return true
var str_2 = "bla.py" // should return false
var str_3 = "bla23.py" // should return false
var str_4 = "bla23_.py" // should return false
I want to make sure that there aren't any foreign characters, while still making sure that I allow everything else (characters like "_", "-", ...).
I'm just trying to avoid the Russian, Mandarin, etc.. alphabets.
You are looking only for ASCII. So something like:
!/^[\x00-\x7F]*$/.test('отправка.py'); // => true
!/^[\x00-\x7F]*$/.test('bla.py'); // => false
Code
See regex in use here
[^ -~]
Alternatively: [^\x00-\x7F] (which seems to have already been posted by #BlakeSimpson)
Usage
const r = /[^ -~]/
const a = [
"отправка.py",
"bla.py",
"bla23.py",
"bla23_.py"
]
a.forEach(function(s) {
if(r.exec(s) !== null) {
console.log(s)
}
})
Explanation
[^ -~] Matches everything that's not from the space character (DEC 32) to the tilde ~ symbol (DEC 126) - which are all the visible ASCII characters.
Also, note that I don't use the g modifier. This is intentional as the OP is only asking to check whether or not there are foreign characters in the string. That means that so long as 1 character exists in the string that meet those requirements it should be matched (no need to match more than one).

Categories