replacing all String in javascript using regex - javascript

i have a dynamic string expression
var expression = "count+count1+12-(count3+count4)";
I want to append v[...] in each string like this output
Output:-
v[count]+v[count1]+12-(v[count3]+v[count4]);
i have tried this regex expression,
expression = expression.replace(/[a-z]+|[A-Z]+/g, "v["/$1/"]").replace(/[\(|\|\.)]/g, "");
is it possible to write regex expression regex string.

You may use
var expression = "count+count1+12-(count3+count4)";
var res = expression.replace(/\b[a-z]\w*/ig, "v[$&]");
console.log(res);
Details:
\b - a leading word boundary
[a-z] - an ASCII letter
\w* - 0+ word chars ([a-zA-Z0-9_]).
The replacement contains $&, a backreference to the whole match.
Another solution that splits with the math operators and only wraps with v[...] those substrings that are not a number or the operator:
var expression = "count+count1+12+234.56-(count3+count4)";
var res = expression.split(/([-+\/*])/).map(function(x) {
return /^(\d*\.?\d+|[-*\/+])$/.test(x) ? x : "v["+x+"]";
}).join("");
console.log(res);

Related

Regular Expression in JavaScript with multiple conditions

I would like to remove in javascript from my text_string all characters that are not letters (in all languages) and numbers. I can do it individually. But how can I put both in ONE expression, so that both conditions are true at the same time?
var text_string = '!#Ab+Z1_↕.🍏2ü翻訳';
text_string = text_string.replace(/\P{Letter}/gu, '');
text_string = text_string.replace(/\P{Number}/gu, '');
text_string = text_string.replace(/[^#]/, '');
// should be replaced to #AbZ12ü翻訳
You can use this regex in unicode for search:
[^\p{Letter}\p{Number}#]+
and replace with empty string.
RegEx Demo
Code:
const regex = /[^\p{Letter}\p{Number}#]+/gu;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('[^\\p{Letter}\\p{Number}#]+', 'gu')
const str = `!#Ab+Z1_↕.🍏2ü翻訳`;
const result = str.replace(regex, '');
console.log(result);
RegEx Breakup:
[^\p{Letter}\p{Number}#]+: In a character class match any character that is not # not a unicode letter and not a unicode number.
Remember that \p{something} is inverse of \P{something}

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>

Split a string according to flanking characters in javascript

Javascript lets you split a string according to regular expression. Is it possible to use this functionality to split a string only when the delimiter is flanked by certain characters?
For example, if I want to split the string 12-93 but not at-13 using the - character? Is that possible?
Using a regular expression seems promising, but doing "12-93".split(/[0-9]-[0-9]/) yields ["1", "3"] because the flanking digits are considered to be part of the delimiter.
Can I specify the above split pattern (a dash preceded and followed by a digit) without chopping the flanking digits?
Other Examples
"55,966,575-165,162,787" should yield ["55,966,575", "165,162,787"]
"55,966,575x-165,162,787" should yield ["55,966,575x-165,162,787"]
"sdf55,966,575-165,162,787" should yield ["sdf55,966,575", "165,162,787"]
Using two adjacent character sets seems to work.
See example at https://regex101.com/r/uFHMW1/1
([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)
Try this (live here https://repl.it/EOOQ/0 ):
var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];
var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');
var matched = strings.map(function (string) {
var matches = string.match( regex );
if (matches) {
return [matches[1], matches[2]];
} else {
return [string];
}
});
console.log(matched)
You can also run the above expression as split() like:
string.split(re).filter( str => str.length )
where Array.filter() is used to get rid of the leading and trailing empty strings created when the RegExp matches your input.
var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];
var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');
var matched = strings.map( string => string.split(regex).filter( str => str.length ) );
console.log(matched)
Try using a non-capturing lookahead. You are using a regex that captures all of the characters found, then uses that result as the split character(s).

JavaScript regex to replace a whole word

I have a variable:
var str = "#devtest11 #devtest1";
I use this way to replace #devtest1 with another string:
str.replace(new RegExp('#devtest1', 'g'), "aaaa")
However, its result (aaaa1 aaaa) is not what I expect. The expected result is: #devtest11 aaaa. I just want to replace the whole word #devtest1.
How can I do that?
Use the \b zero-width word-boundary assertion.
var str = "#devtest11 #devtest1";
str.replace(/#devtest1\b/g, "aaaa");
// => #devtest11 aaaa
If you need to also prevent matching the cases like hello#devtest1, you can do this:
var str = "#devtest1 #devtest11 #devtest1 hello#devtest1";
str.replace(/( |^)#devtest1\b/g, "$1aaaa");
// => #devtest11 aaaa
Use word boundary \b for limiting the search to words.
Because # is special character, you need to match it outside of the word.
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W), since \b does not include special characters.
var str = "#devtest11 #devtest1";
str = str.replace(/#devtest1\b/g, "aaaa");
document.write(str);
If your string always starts with # and you don't want other characters to match
var str = "#devtest11 #devtest1";
str = str.replace(/(\s*)#devtest1\b/g, "$1aaaa");
// ^^^^^ ^^
document.write(str);
\b won't work properly if the words are surrounded by non space characters..I suggest the below method
var output=str.replace('(\s|^)#devtest1(?=\s|$)','$1aaaa');

How to add white space in regular expression in Javascript

I have a string {{my name}} and i want to add white space in regular expression
var str = "{{my name}}";
var patt1 = /\{{\w{1,}\}}/gi;
var result = str.match(patt1);
console.log(result);
But result in not match.
Any solution for this.
Give the word character\w and the space character\s inside character class[],
> var patt1 = /\{\{[\w\s]+\}\}/gi;
undefined
> var result = str.match(patt1);
undefined
> console.log(result);
[ '{{my name}}' ]
The above regex is as same as /\{\{[\w\s]{1,}\}\}/gi
Explanation:
\{ - Matches a literal { symbol.
\{ - Matches a literal { symbol.
[\w\s]+ - word character and space character are given inside Character class. It matches one or more word or space character.
\} - Matches a literal } symbol.
\} - Matches a literal } symbol.
Try this on
^\{\{[a-z]*\s[a-z]*\}\}$
Explanation:
\{ - Matches a literal { symbol.
\{ - Matches a literal { symbol.
[a-z]* - will match zero or more characters
\s - will match exact one space
\} - Matches a literal } symbol.
\} - Matches a literal } symbol.
If you want compulsory character then use + instead of *.
To match this pattern, use this simple regex:
{{[^}]+}}
The demo shows you what the pattern matches and doesn't match.
In JS:
match = subject.match(/{{[^}]+}}/);
To do a replacement around the pattern, use this:
result = subject.replace(/{{[^}]+}}/g, "Something$0Something_else");
Explanation
{{ matches your two opening braces
[^}]+ matches one or more chars that are not a closing brace
}} matches your two closing braces

Categories

Resources