How to add white space in regular expression in Javascript - 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

Related

Is there a regex to remove everything after comma in a string except first letter

I am trying to remove all the characters from the string after comma except the first letter. The string is basically the last name,first name.
For example:
Smith,John
I tried as below but it removes comma and everything after comma.
let str = "Smith,John";
str = str.replace(/\s/g, ""); // to remove all whitespace if there is any at the beginning, in the middle and at the end
str = str.split(',')[0];
Expected output: Smith,J
Thank you!
Or try (,\w).* with replace:
let str = "Smith,John";
str = str.replace(/(,\w).*/, '$1');
console.log(str);
Try this regex out:
\w+,\w
This matches one or more characters before the comma and then matches only 1 character.
Here is the demo: https://regex101.com/r/bKpWt7/1
Note: \w matches any character from [a-zA-Z0-9_].
Taking optional spaces around the comma in to account, and perhaps multiple "names" before the comma:
*([^\s,][^,\n]*?) *, *([^\s,]).*
* Match optional spaces
( Capture group 1
*([^\s,] Match optional spaces and match at least a single char other than a whitespace char or a ,
[^,\n]*? Match any char except a , or a newline non greedy
) Close group 1
*, * Match a comma between optional spaces
([^\s,]) Capture group 2, match a single char other than , or a whitespace char
.* Match the rest of the line
Regex demo
In the replacement using group 1 and group 2 with a comma in between $1,$2
const regex = / *([^\s,][^,\n]*?) *, *([^\s,]).*/;
[
"Smith,John Jack",
"Smith Lastname , Jack John",
"Smith , John",
" ,Jack"
].forEach(s => console.log(s.replace(regex, "$1,$2")));

Validate string in regular expression

I want to have a regular expression in JavaScript which help me to validate a string with contains only lower case character and and this character -.
I use this expression:
var regex = /^[a-z][-\s\.]$/
It doesn't work. Any idea?
Just use
/^[a-z-]+$/
Explanation
^ : Match from beginning string.
[a-z-] : Match all character between a-z and -.
[] : Only characters within brackets are allowed.
a-z : Match all character between a-z. Eg: p,s,t.
- : Match only strip (-) character.
+ : The shorthand of {1,}. It's means match 1 or more.
$: Match until the end of the string.
Example
const regex= /^[a-z-]+$/
console.log(regex.test("abc")) // true
console.log(regex.test("aBcD")) // false
console.log(regex.test("a-c")) // true
Try this:
var regex = /^[-a-z]+$/;
var regex = /^[-a-z]+$/;
var strs = [
"a",
"aB",
"abcd",
"abcde-",
"-",
"-----",
"a-b-c",
"a-D-c",
" "
];
strs.forEach(str=>console.log(str, regex.test(str)));
Try this
/^[a-z-]*$/
it should match the letters a-z or - as many times as possible.
What you regex does is trying to match a-z one single time, followed by any of -, whitespace or dot one single time. Then expect the string to end.
Use this regular expression:
let regex = /^[a-z\-]+$/;
Then:
regex.test("abcd") // true
regex.test("ab-d") // true
regex.test("ab3d") // false
regex.test("") // false
PS: If you want to allow empty string "" to pass, use /^[a-z\-]*$/. Theres an * instead of + at the end. See Regex Cheat Sheet: https://www.rexegg.com/regex-quickstart.html
I hope this helps
var str = 'asdadWW--asd';
console.log(str.match(/[a-z]|\-/g));
This will work:
var regex = /^[a-z|\-|\s]+$/ //For this regex make use of the 'or' | operator
str = 'test- ';
str.match(regex); //["test- ", index: 0, input: "test- ", groups: undefined]
str = 'testT- ' // string now contains an Uppercase Letter so it shouldn't match anymore
str.match(regex) //null

replacing all String in javascript using regex

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

Split string by all spaces except those in parentheses

I'm trying to split text the following like on spaces:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}"
but I want it to ignore the spaces within parentheses. This should produce an array with:
var words = ["Text", "(what is)|what's", "a", "story|fable" "called|named|about", "{Search}|{Title}"];
I know this should involve some sort of regex with line.match(). Bonus points if the regex removes the parentheses. I know that word.replace() would get rid of them in a subsequent step.
Use the following approach with specific regex pattern(based on negative lookahead assertion):
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}",
words = line.split(/(?!\(.*)\s(?![^(]*?\))/g);
console.log(words);
(?!\(.*) ensures that a separator \s is not preceded by brace ((including attendant characters)
(?![^(]*?\)) ensures that a separator \s is not followed by brace )(including attendant characters)
Not a single regexp but does the job. Removes the parentheses and splits the text by spaces.
var words = line.replace(/[\(\)]/g,'').split(" ");
One approach which is useful in some cases is to replace spaces inside parens with a placeholder, then split, then unreplace:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}";
var result = line.replace(/\((.*?)\)/g, m => m.replace(' ', 'SPACE'))
.split(' ')
.map(x => x.replace(/SPACE/g, ' '));
console.log(result);

Javascript strip Latex form of English letter variants

How can I replace Latex characters using {\'<1 alpha>} pattern with corresponding English letter?
For example
L{\'o}pez
Should change to
Lopez
It should not affect any other character out of {\'<1 alpha>} pattern. It should be greedy as well since there might be several characters required to be pruned.
$1 was made for this:
var new_string = 'L{\\\'o}pez'.replace(/\{\\['"]([A-Z])\}/gi, '$1');
The extra \ are so we can escape the \ and the '.
Explained:
\{ Selects a {
\\ Selects a \
(?: Starts a group that is not "stored"
\' Selects a quote
| OR
\" Selects a double quote
) Ends the group
([A-Z]) Takes one alphabetical character and stores it in a group
\} Selects a } to end the selection
g: Selects multiple times
i: Case in-sensitive. [A-Z] becomes: [A-Za-z]
{\\'([a-zA-Z])}
Try this.Replace by $1.See demo.
https://regex101.com/r/oF9hR9/3
var re = /{\\'([a-zA-Z])}/g;
var str = 'L{\'o}pez';
var subst = '$1';
var result = str.replace(re, subst);
You can use a regex like following :
var str = "L{\'o}pez";
var res = str.replace(/{\\'([a-zA-Z])}/g, /$1/);
\S will match a alphabetical character and the preceding replace function will replace the match regex /{\'([a-zA-Z])}/g with first group $1 that is your character ([a-zA-Z]).

Categories

Resources