how to find comma or other symbols in a string using javascript? - javascript

Let's assume I have an string... I want to convert them to numbers.. and It will only work for alphabets...
if my string contains comma or dot... I would like to avoid it...
I'm working with words by word. so if the string is--
"Hi, let's play!"
it should be converted to--
"4510, 584578'52 69775246!"
how can I do it?
function hasNumber(gottenWord) {
return (/\d/.test(gottenWord));
}
const numberTrue = hasNumber(gottenWord);
I was able to search for numbers but not sure how to search for symbols.. and I even have some custom symbols to search.

If all you want is to avoid anything that's not in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ then the easiest way is to change \d to [^a-zA-Z]. [] indicates a character set, and starting a set with ^ means "not these".

Related

How to get content using filter and match?

I want to search in the array if theres the string that Im looking for, to do that im using match
const search_notes = array_notes.filter(notes => notes.real_content.toUpperCase().match(note.toUpperCase()));
as you can see, search_notes will give me an array with all the strings that at least has a character from the input or match completely, but theres a problem, because when I write , ), [], + or any regex symbol in the input it will gives me this error:
how can i solve this?
If you look at documentation for the match method (for instance, MDN's), you'll see that it accepts a RegExp object or a string, and if you give it a string, it passes that string into new RegExp. So naturally, characters that have special meaning in a regular expression need special treatment.
You don't need match, just includes, which doesn't do that:
const search_notes = array_notes.filter(
notes => notes.real_content.toUpperCase().includes(note.toUpperCase())
);

check whether csv form or not [duplicate]

What is the regular expression to validate a comma delimited list like this one:
12365, 45236, 458, 1, 99996332, ......
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
Reference.
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Reference.
/^\d+(?:, ?\d+)*$/
i used this for a list of items that had to be alphanumeric without underscores at the front of each item.
^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$
You might want to specify language just to be safe, but
(\d+, ?)+(\d+)?
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(#"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like #"([0-9]+),\s?" and parse on Groups[0].
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
In JavaScript, use split to help out, and catch any negative digits as well:
'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
The following will match any comma delimited word/digit/space combination
(((.)*,)*)(.)*
Why don't you work with groups:
^(\d+(, )?)+$
If you had a more complicated regex, i.e: for valid urls rather than just numbers. You could do the following where you loop through each element and test each of them individually against your regex:
const validRelativeUrlRegex = /^(^$|(?!.*(\W\W))\/[a-zA-Z0-9\/-]+[^\W_]$)/;
const relativeUrls = "/url1,/url-2,url3";
const startsWithComma = relativeUrls.startsWith(",");
const endsWithComma = relativeUrls.endsWith(",");
const areAllURLsValid = relativeUrls
.split(",")
.every(url => validRelativeUrlRegex.test(url));
const isValid = areAllURLsValid && !endsWithComma && !startsWithComma

Matching and returning a regex between two values

I am trying to get the values from a string using regex, the value is that of the text between tt=" and "&
So, for example, "tt="Value"&" I would only want to get the word "Value" out of this.
So far I have this: /tt=.*&/ which gives me "tt=Value"&, Then, to get the value I am thinking to split the match on = and remove the 2 characters from the end. I feel though, that this would be an awful way to do this and would like to see if it could be done in the regex?
You're on the right track for matching the entire context inside of the string, but you want to use a capturing group to match/capture the value between the quotes instead of splitting on = and having to remove the two quote chars.
var r = 'tt="Value"&'.match(/tt="([^"]*)"/)[1];
if (r)
console.log(r); //=> "Value"
I know this isn't really the answer you are looking for since it doesn't involve regex but it's the way I usually do it.
strvariable = strvariable.Remove(0,strvariable.IndexOf("=") + 2);
strvariable = strvariable.Remove(strvariable.IndexOf("\""), strvariable.Length - strvariable.IndexOf("\""));
this would give you the result you were looking for which is Value in this instance.

Get string between tags when multiple tags present

Just trying to figure this one out as regex is nowhere near my strong point :(
Basically I'm trying to get the value between bbcode tags: That could look like either of the following:
[center]text[/center]
[left][center]text[/center][/left]
[right][left][center]text[/center][/left][/right]
And currently have this hideous if else block of code to prevent it getting large like the third option above.
if (/\[left\]|\[\/left\]/.test(text[2])) {
// set the value in the [left][/left] tags
text[2] = text[2].match(/\[left\](.*?)\[\/left\]/)[1];
} else if (/\[right\]|\[\/right\]/.test(text[2])) {
// set value in the [right][/right] tags
text[2] = text[2].match(/\[right\](.*?)\[\/right\]/)[1];
} else if (/\[center\]|\[\/center\]/.test(text[2])) {
// set value in the [right][/right] tags
text[2] = text[2].match(/\[center\](.*?)\[\/center\]/)[1];
}
What I'd like to do is shorten it down to a single regex expression to grab that value text from the above examples, I've gotten down to an expression like this:
/\[(?:center|left|right)\](.*?)\[\/(?:center|left|right)\]/
But as you can see in this RegExr demo, it doesn't match what I need it to.
How can I achieve this?
Note
It should only match left|right|center as the selected text could also have various other bbcode tags.
If the string looks like this:
[center][left][img]/link/to/img.png[/img][/left][/center]
I want to get what is between the left|center|right tags which in this case would be:
[img]/link/to/img.png[/img]
More examples:
[center][url=lintosomething.com]LINK TEXT[/url][/center]
Should only get: [url=lintosomething.com]LINK TEXT[/url]
Or
[center]egibibskdfbgfdkfbg sd fgkgb fkgbgk fhwo3g regbiurb geir so go to [url=lintosomething.com]LINK TEXT[/url] and ibgri gbenkenbieurgnerougnerogrnreog erngo[/center]
Wanting:
egibibskdfbgfdkfbg sd fgkgb fkgbgk fhwo3g regbiurb geir so go to [url=lintosomething.com]LINK TEXT[/url] and ibgri gbenkenbieurgnerougnerogrnreog erngo
Edit: Ok, I think this fits your needs.
My regex:
/[^\]\[]*\[(\w+)[=\.\"\w]*\][^\]]+\[\/\1\][^\]\[]*/g
Explanation:
Match 0 or more characters that arent [ or ]
Match a single [
Match 1 or more of alpha characters, we'll use this later as a backreference
Match 0 or more of = . " or alpha characters
Match a single ]
Match 1 or more non [ characters
Match a single [
Match a single /
Match the same characters as step 3. (Our back reference)
Match a single ]
Match 0 or more characters that arent [ or ]
See it in action
However I would like to state that if you're going to be parsing bbcodes you're almost certainly better off just using a bbparser.
Why not just replace all those tags with empty string
var rawString; // your input string
var cleanedString = rawString.replace(~\[/?(left|right|center)\]~, '');
You could use a capturing group like this:
(?:\[\w+\])*(\w+)(?:\[\/\w+\])*
Or with a capture group named "value" like this:
(?:\[\w+\])*(?<value>\w+)(?:\[\/\w+\])*
The first and last groups are non-capturing... (?: ...)
And the middle group is capturing (\w+)
And the middle group if named like this (?<value>\w+)
Note: For simplicity, I replaced your center|left|right values with \w+ but you could swap them back in with no impact.
I use an app called RegExRX. Here's a screenshot with the RegEx and captured values.
Lots of ways you could tweak it. Good luck!

regex search a string for contents between two strings

I am trying my upmost best to get my head around regex, however not having too much luck.
I am trying to search within a string for text, I know how the string starts, and i know how the string ends, I want to return ALL the text inbetween the string including the start and end.
Start search = [{"lx":
End search = }]
i.e
[{"lx":variablehere}]
So far I have tried
/^\[\{"lx":(*?)\}\]/;
and
/(\[\{"lx":)(*)(\}\])/;
But to no real avail... can anyone assist?
Many thanks
You're probably making the mistake of believing the * is a wildcard. Use the period (.) instead and you'll be fine.
Also, are you sure you want to stipulate zero or more? If there must be a value, use + (one or more).
Javascript:
'[{"lx":variablehere}]'.match(/^\[\{"lx":(.+?)\}\]/);
The * star character multiplies the preceding character. In your case there's no such character. You should either put ., which means "any character", or something more specific like \S, which means "any non whitespace character".
Possible solution:
var s = '[{"lx":variablehere}]';
var r = /\[\{"(.*?)":(.*?)\}\]/;
var m = s.match(r);
console.log(m);
Results to this array:
[ '[{"lx":variablehere}]',
'lx',
'variablehere',
index: 0,
input: '[{"lx":variablehere}]' ]
\[\{"lx"\:(.*)\}\]
This should work for you. You can reach the captured variable by \1 notation.
Try this:
^\[\{\"lx\"\:(.*)\}\]$
all text between [{"lx": and }] you will find in backreference variable (something like \$1 , depends on programming language).

Categories

Resources