javascript replace all - javascript

I have a sting like:
var tmp='Hello
I am
( Peter';
I want to replace all words with this pattern &...; to '';
How I can change the code below to make it work:
tmp=String(tmp).replace(/
/g, "");
Thank you.

Update regex with \d{2} instead of the 10 to match any two digit numbers.
var tmp = 'Hello
I am
( Peter';
tmp = String(tmp).replace(/&#\d{2};/g, "");
console.log(tmp);

try this /&#(\d+)(;)/g .Its match the numbers upto reach of ; end
Normal Regex
var tmp='Hello
I am
( Peter';
console.log(tmp.replace(/&#(\d+)(;)/g,""))
Remove the Empty space also use: /(\s+)&#(\d+)(;)/g .\s+ match the empty space before the pattern
Empty space match
var tmp='Hello
I am
( Peter';
console.log(tmp.replace(/(\s+)&#(\d+)(;)/g,""))

Related

How to slice optional arguments in RegEx?

Actually i have the following RegExp expression:
/^(?:(?:\,([A-Za-z]{5}))?)+$/g
So the accepted input should be something like ,IGORA but even ,IGORA,GIANC,LOLLI is valid and i would be able to slice the string to 3 group in this case, in other the group number should be equals to the user input that pass the RegExp test.
i was trying to do something like this in JavaScript but it return only the last value
var str = ',GIANC,IGORA';
var arr = str.match(/^(?:(?:\,([A-Za-z]{5}))?)+$/).slice(1);
alert(arr);
So the output is 'IGORA' while i would it to be 'GIANC' 'IGORA'
Here is another example
/^([A-Z]{5})(?:(?:\,([A-Za-z]{2}))?)+$/g
test of regexp may have at least 5 chart string but it also can have other 5 chart string separated with a comma so from input
IGORA,CIAOA,POPOP
I would have an array of ["IGORA","CIAOA","POPOP"]
You can capture the words in a capturing surrounded by an optional preceding comma or an optional trailing comma.
You can test the regex here: ,?([A-Za-z]+),?
const pattern = /,?([A-Za-z]+),?/gm;
const str = `,IGORA,GIANC,LOLLI`;
let matches = [];
let match;
// Iterate until no match found
while ((m = pattern.exec(str))) {
// The first captured group is the match
matches.push(m[1]);
}
console.log(matches);
There are other ways to do this, but I found that one of the simple ways is by using the replace method, as it can replace all instances that match that regex.
For example:
var regex = /^(?:(?:\,([A-Za-z]{5}))?)+$/g;
var str = ',GIANC,IGORA';
var arr = [];
str.replace(regex, function(match) {
arr[arr.length] = match;
return match;
});
console.log(arr);
Also, in my code snippet you can see that there is an extra coma in each string, you can solve that by changing line 5 to arr[arr.length] = match.replace(/^,/, '').
Is this what you're looking for?
Explanation:
\b word boundary (starting or ending a word)
\w a word ([A-z])
{5} 5 characters of previous
So it matches all 5-character words but not NANANANA
var str = 'IGORA,CIAOA,POPOP,NANANANA';
var arr = str.match(/\b\w{5}\b/g);
console.log(arr); //['IGORA', 'CIAOA', 'POPOP']
If you only wish to select words separated by commas and nothing else, you can test for them like so:
(?<=,\s*|^) preceded by , with any number of trailing space, OR is the first word in list.
(?=,\s*|$) followed by , and any number of trailing spaces OR is last word in list.
In the following code, POPOP and MOMMA are rejected because they are not separated by a comma, and NANANANA fails because it is not 5 character.
var str = 'IGORA, CIAOA, POPOP MOMMA, NANANANA, MEOWI';
var arr = str.match(/(?<=,\s*|^)\b\w{5}\b(?=,\s*|$)/g);
console.log(arr); //['IGORA', 'CIAOA', 'MEOWI']
If you can't have any trailing spaces after the comma, just leave out the \s* from both (?<=,\s*|^) and (?=,\s*|$).

Finding ++ in Regular Expression

I want to find ++ or -- or // or ** sign in in string can anyone help me?
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = ++,--,//,**;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
This finds doubles of the characters by a backreference:
/([+\/*-])\1/g
[from q. comments]: i know this but when i type var patt1 = /[++]/i; code find + and ++
[++] means one arbitrary of the characters. Normally + is the qantifier "1 or more" and needs to be escaped by a leading backslash when it should be a literal, except in brackets where it does not have any special meaning.
Characters that do need to be escaped in character classes are e.g. the escape character itself (backslash), the expression delimimiter (slash), the closing bracket and the range operator (dash/minus), the latter except at the end of the character class as in my code example.
A character class [] matches one character. A quantifier, e.g. [abc]{2} would match "aa", "bb", but "ab" as well.
You can use a backreference to a match in parentheses:
/(abc)\1
Here the \1 refers to the first parentheses (abc). The entire expression would match "abcabc".
To clarify again: We could use a quantifier on the backreference:
/([+\/*-])\1{9}/g
This matches exactly 10 equal characters out of the class, the subpattern itself and 9 backreferences more.
/.../g finds all occurrences due to the modifier global (g).
test-case on regextester.com
Define your pattern like this:
var patt1 = /\+\+|--|\/\/|\*\*/;
Now it should do what you want.
More info about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can use:
/\+\+|--|\/\/|\*\*/
as your expression.
Here I have escaped the special characters by using a backslash before each (\).
I've also used .test(str) on the regular expression as all you need is a boolean (true/false) result.
See working example below:
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = patt1.test(res);
if (result) {
alert("you cant do this :l");
document.getElementById('screen').innerHTML = '';
}
<div id="screen">
This is some++ text
</div>
Try this:-
As
n+:- Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
We need to use backslash before this special characters.
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
<div id="screen">2121++</div>

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

JS - Split string into substrings by regex

Let's say I have a string that starts by 7878 and ends by 0d0a or 0D0A such as:
var string = "78780d0101234567890123450016efe20d0a";
var string2 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a";
var string 3 = "78780d0101234567890123450016efe20d0a78780d0103588990504943870016efe20d0a78780d0101234567890123450016efe20d0a"
How can I split it by regex so it becomes an array like:
['78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
['78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a','78780d0101234567890123450016efe20d0a']
You can split the string with a positive lookahead (?=7878). The regex isn't consuming any characters, so 7878 will be part of the string.
var rgx = /(?=7878)/;
console.log(string1.split(rgx));
console.log(string2.split(rgx));
console.log(string3.split(rgx));
Another option is to split on '7878' and then take all the elements except first and add '7878' to each of them. For example:
var arr = string3.split('7878').slice(1).map(function(str){
return '7878' + str;
});
That works BUT it also matches strings that do NOT end on 0d0a. How
can I only matches those ending on 0d0a OR 0D0A?
Well, then you can use String.match with a plain regex.
console.log(string3.match(/7878.*?0d0a/ig));

Javascript Regex for capturing variables in curved brackets

I have a string that is being fed into a JavaScript function and I need to pull the variables out of it.
var str = "heres:a:func('var1', 'var2', 'var3', 2)"
I'm getting close, but would like to do it with one regex.
str.match(/\((.*)\)/)[1].split(/\s*,\s*/)
Results should look like this:
['var1', 'var2', 'var3', 2]
Here's one way to do it:
Regex101 Link
This does not include the quotes by the way, you can add those optionally if you want.
var pattern = /(\w+)(?!.*\()(?=.*\))/g;
var str = "heres:a:func('var1', 'var2', 'var3', 2)";
var matches = str.match(pattern);
console.log(matches); //['var1','var2','var3','2']
This basically searches for a word character group, and then does a negative and positive lookahead.
Basically
(?!.*\()
says that I want this to NOT be before any number of characters plus a ( character and
(?=.*\))
says that i WANT this to be before any number of characters and a ) character.
Then the capturing group is at the beginning, so you could replace (\w+) with ([\'\w]+) if you wanted to keep the quotes (which I don't think you would right)
Edit: To include spaces in your strings, you can do something like this:
var pattern = /([\w]+\s[\w]+|\w+)(?!.*\()(?=.*\))/g
But that will not capture trailing white space, just spaces surrounded by 2 word types (a-Z0-1). Also that only will allow 1 space in the word, so if you need multiples, you'd have to check for that as well. You could modify it to check for any number of word characters or spaces between 2 valid word characters.
For Multiple Spaces:
var pattern = /([\w]+[\s\w]*[\w]+|\w+)(?!.*\()(?=.*\))/g
Includes 1 Space: Regex101 Link
Includes Multiple Spaces: Regex101 Link
Edit2:
And just as a final one, if you REALLY want to add a bunch of spaces throughout, you can do this one:
Includes Multiple Spaces, Multiple Times: Regex101 Link
/([\w]+[\s\w]+[\w]+|\w+)(?!.*\()(?=.*\))/g
This should do ('\w+'|\d+) it captures words (\w = alphanumeric and hyphen) between single quote or (|) numeric unquoted values.
See the demo here
For a code exemple:
var str = "heres:a:func('var1', 'var2', 'var3', 2)"
var reg=new RegExp("('\\w+'|\\d+)", "g");
var i= 0;
var arr = [];
str.replace(reg,function(m,group) {arr[i++]=group})
console.log(arr) gives:
["'var1'", "'var2'", "'var3'", "2"]
As i can't add a comment i post a answer.
var str = "heres:a:func('var1', 'var2', 'var3', 2)"
var args = /\(\s*([^)]+?)\s*\)/.exec(str);
if (args[1]) {
args = args[1].split(/\s*,\s*/);
console.log(args);
alert(args);
}
or try it out here:
https://jsfiddle.net/oz3Ljfe1/3/
You can do it with one line, but still 2 regexps: 1) remove all up to the opening ( and the closing ), then split on the commas with optional whitespace. This way we'll get all the vars, regardless of how many there are variables.
var str = "heres:a:func('var1', 'var2', 'var3', 2)";
alert(str.replace(/.*\(|\s*\)\s*$/g, '').split(/\s*,\s*/));
Also, you might try a kind of a fancy regex, but it is not that safe (only works if you have correctly formatted data):
var re = /('[^']*?'|\b\d+\b),?(?=(?:(?:[^']*'){2})*[^']*\)$)/g;
var str = 'heres:a:func23(\'var1\', \'var2\', \'var3\', 2, \'2345\')';
while ((m = re.exec(str)) !== null) {
document.getElementById("res").innerHTML += m[1] + "<br/>";
}
<div id="res"/>

Categories

Resources