Detect repeating letter in an string in Javascript - javascript

code for detecting repeating letter in a string.
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string

JSFIDDLE
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.

Try this:
var str = "paraven4sr";
function checkDuplicate(str){
for(var i = 0; i < str.length; i++){
var re = new RegExp("[^"+ str[i] +"]","g");
if(str.replace(re, "").length >= 2){
return true;
}
}
return false;
}
alert(checkDuplicate(str));
Here is jsfiddle

To just test duplicate alphanumeric character (including underscore _):
console.log(/(\w)\1+/.test('aab'));

Something like this?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)

Related

Replace after char '-' or '/' match

I'm trying to execute regex replace after match char, example 3674802/3 or 637884-ORG
The id can become one of them, in that case, how can I use regex replace to match to remove after the match?
Input var id = 3674802/3 or 637884-ORG;
Expected Output 3674802 or 637884
You could use sbustring method to take part of string only till '/' OR '-':
var input = "3674802/3";
var output = input.substr(0, input.indexOf('/'));
var input = "637884-ORG";
var output = input.substr(0, input.indexOf('-'));
var input = "3674802/3";
if (input.indexOf('/') > -1)
{
input = input.substr(0, input.indexOf('/'));
}
console.log(input);
var input = "637884-ORG";
if (input.indexOf('-') > -1)
{
input = input.substr(0, input.indexOf('-'));
}
console.log(input);
You can use a regex with a lookahead assertion
/(\d+)(?=[/-])/g
var id = "3674802/3"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
id = "637884-ORG"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
You don't need Regex for this. Regex is far more powerful than what you need.
You get away with the String's substring and indexOf methods.
indexOf takes in a character/substring and returns an integer. The integer represents what character position the character/substring starts at.
substring takes in a starting position and ending position, and returns the new string from the start to the end.
If are having trouble getting these to work; then, feel free to ask for more clarification.
You can use the following script:
var str = '3674802/3 or 637884-ORG';
var id = str.replace(/(\d+)[-\/](?:\d+|[A-Z]+)/g, '$1');
Details concerning the regex:
(\d+) - A seuence of digits, the 1st capturing group.
[-\/] - Either a minus or a slash. Because / are regex delimiters,
it must be escaped with a backslash.
(?: - Start of a non-capturing group, a "container" for alternatives.
\d+ - First alternative - a sequence of digits.
| - Alternative separator.
[A-Z]+ - Second alternative - a sequence of letters.
) - End of the non-capturing group.
g - global option.
The expression to replace with: $1 - replace the whole finding with
the first capturing group.
Thanks To everyone who responded to my question, was really helpful to resolve my issue.
Here is My answer that I built:
var str = ['8484683*ORG','7488575/2','647658-ORG'];
for(i=0;i<str.length;i++){
var regRep = /((\/\/[^\/]+)?\/.*)|(\-.*)|(\*.*)/;
var txt = str[i].replace(regRep,"");
console.log(txt);
}

Replace string with condition in google script

in google script I am trying to replace a %string basing on the character following it.
I've tried using:
var indexOfPercent = newString.indexOf("%");
and then check the character of indexOfPercent+1, but indexOf returns only the first occurrence of '%'.
How can I get all occurrences? Maybe there is easier way to do that (regular expressions)?
EDIT:
Finally I want to replace all my % occurrences to %%, but not if percent sign was part of %# or %#.
To sum up: my string: Test%# Test2%s Test3%. should look like: Test%# Test2%s Test3%%.
I've tried using something like this:
//?!n Matches any string that is not followed by a specific string n
//(x|y) Find any of the alternatives specified
var newString = newString.replace(\%?![s]|\%?![%], "%%")
but it didn't find any strings. I am not familiar with regex's, so maybe it is a simple mistake.
Thanks
Try this code:
// replace all '%'
var StrPercent = '%100%ffff%';
var StrNoPersent = StrPercent.replace(/\%/g,'');
Logger.log(StrNoPersent); // 100ffff
Look for more info here
Edit
In your case you need RegEx with the character not followed by group of characters. Similiar question was asked here:
Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?
Thy this code:
function RegexNotFollowedBy() {
var sample = ['Test%#',
'Test2%s',
'Test3%',
'%Test4%'];
var RegEx = /%(?!s|#)/g;
var Replace = "%%";
var str, newStr;
for (var i = 0; i < sample.length; i++) {
str = sample[i];
newStr = str.replace(RegEx, Replace);
Logger.log(newStr);
}
}
I'll explain expression /%(?!s|#)/g:
% -- look '%'
(text1|text2|text3...|textN) -- not followed by text1, 2 etc.
g -- look for any accurance of searched text

Extract word between '=' and '('

I have the following string
234234=AWORDHERE('sdf.'aa')
where I need to extract AWORDHERE.
Sometimes there can be space in between.
234234= AWORDHERE('sdf.'aa')
Can I do this with a regular expression?
Or should I do it manually by finding indexes?
The datasets are huge, so it's important to do it as fast as possible.
Try this regex:
\d+=\s?(\w+)\(
Check Demo
in Javascript it would like that:
var myString = "234234=AWORDHERE('sdf.'aa')";// or 234234= AWORDHERE('sdf.'aa')
var myRegexp = /\d+=\s?(\w+)\(/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // AWORDHERE
You could do this at least three ways. You need to benchmark to see what's fastest.
Substring w/ indexes
function extract(from) {
var ixEq = from.indexOf("=");
var ixParen = from.indexOf("(");
return from.substring(ixEq + 1, ixParen);
}
.
Splits
function extract(from) {
var spEq = from.split("=");
var spParen = spEq[1].split("(");
return spParen[0];
}
Regex (demo)
Here is some sample regex you could use
/[^=]+=([^(]+).*/g
This says
[^=]+ - One or more character which is not an =
= - The = itself
( - creates a matching group so you can access your match in code
[^(]+ - One or more character which is not a (
) - closes the matching group
.* - Matches the rest of the line
the /g on the end tells it to perform the match on all lines.
Using look around you can search for string preceded by = and followed by ( as following.
Regex: (?<==)[A-Z ]+(?=\()
Explanation:
(?<==) checks if [A-Z ] is preceded by an =.
[A-Z ]+ matches your pattern.
(?=\() checks if matched pattern is followed by a (.
Regex101 Demo
var str = "234234= AWORDHERE('sdf.'aa')";
var regexp = /.*=\s+(\w+)\(.*\)/g;
var match = regexp.exec(str);
alert( match[1] );
I made my solution for this just a little more general than you asked for, but I don't think it takes much more time to execute. I didn't measure. If you need greater efficiency than this provides, comment and I or someone else can help you with that.
Here's what I did, using the command prompt of node:
> var s = "234234= AWORDHERE('sdf.'aa')"
undefined
> var a = s.match(/(\w+)=\s*(\w+)\s*\(.*/)
undefined
> a
[ '234234= AWORDHERE(\'sdf.\'aa\')',
'234234',
'AWORDHERE',
index: 0,
input: '234234= AWORDHERE(\'sdf.\'aa\')' ]
>
As you can see, this matches the number before the = in a[1], and it matches the AWORDHERE name as you requested in a[2]. This will work with any number (including zero) spaces before and/or after the =.

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

Why is my RegExp ignoring start and end of strings?

I made this helper function to find single words, that are not part of bigger expressions
it works fine on any word that is NOT first or last in a sentence, why is that?
is there a way to add "" to regexp?
String.prototype.findWord = function(word) {
var startsWith = /[\[\]\.,-\/#!$%\^&\*;:{}=\-_~()\s]/ ;
var endsWith = /[^A-Za-z0-9]/ ;
var wordIndex = this.indexOf(word);
if (startsWith.test(this.charAt(wordIndex - 1)) &&
endsWith.test(this.charAt(wordIndex + word.length))) {
return wordIndex;
}
else {return -1;}
}
Also, any improvement suggestions for the function itself are welcome!
UPDATE: example: I want to find the word able in a string, I waht it to work in cases like [able] able, #able1 etc.. but not in cases that it is part of another word like disable, enable etc
A different version:
String.prototype.findWord = function(word) {
return this.search(new RegExp("\\b"+word+"\\b"));
}
Your if will only evaluate to true if endsWith matches after the word. But the last word of a sentence ends with a full stop, which won't match your alphanumeric expression.
Did you try word boundary -- \b?
There is also \w which match one word character ([a-zA-Z_]) -- this could help you too (depends on your word definition).
See RegExp docs for more details.
If you want your endsWith regexp also matches the empty string, you just need to append |^$ to it:
var endsWith = /[^A-Za-z0-9]|^$/ ;
Anyway, you can easily check if it is the beginning of the text with if (wordIndex == 0), and if it is the end with if (wordIndex + word.length == this.length).
It is also possible to eliminate this issue by operating on a copy of the input string, surrounded with non-alphanumerical characters. For example:
var s = "#" + this + "#";
var wordIndex = this.indexOf(word) - 1;
But I'm afraid there is another problems with your function:
it would never match "able" in a string like "disable able enable" since the call to indexOf would return 3, then startsWith.test(wordIndex) would return false and the function would exit with -1 without searching further.
So you could try:
String.prototype.findWord = function (word) {
var startsWith = "[\\[\\]\\.,-\\/#!$%\\^&\*;:{}=\\-_~()\\s]";
var endsWith = "[^A-Za-z0-9]";
var wordIndex = ("#"+this+"#").search(new RegExp(startsWith + word + endsWith)) - 1;
if (wordIndex == -1) { return -1; }
return wordIndex;
}

Categories

Resources