Javascript function to remove leading dot - javascript

I have a javascript string which have a leading dot. I want to remove the leading dot using javascript replace function. I tried the following code.
var a = '.2.98»';
document.write(a.replace('/^(\.+)(.+)/',"$2"));
But this is not working. Any Idea?

The following replaces a dot in the beginning of a string with an empty string leaving the rest of the string untouched:
a.replace(/^\./, "")

Don't do regexes if you don't need to.
A simple charAt() and a substring() or a substr() (only if charAt(0) is .) will be enough.
Resources:
developer.mozilla.org: charAt()
developer.mozilla.org: substring()
developer.mozilla.org: substr()

Your regex is wrong.
var a = '.2.98»';
document.write(a.replace('/^\.(.+)/',"$1"));
You tried to match (.+) to the leading dot, but that doesn't work, you want \. instead.

Keep it simple:
if (a.charAt(0)=='.') {
document.write(a.substr(1));
} else {
document.write(a);
}

Related

regex to match dot and number follow the dot

I need to check a string in javascript if it contains dot followed by number (ex: xx.12) using regex
What is the correct regex for that.
You could try
let pat = /\.[0-9]/
if(pat.test(number))
{
//do something
}
correct regex to match your string is "xx\.12"
Backslash makes regex to take the next dot as a dot but not as anything.

How to replace string between two string with the same length

I have an input string like this:
ABCDEFG[HIJKLMN]OPQRSTUVWXYZ
How can I replace each character in the string between the [] with an X (resulting in the same number of Xs as there were characters)?
For example, with the input above, I would like an output of:
ABCDEFG[XXXXXXX]OPQRSTUVWXYZ
I am using JavaScript's RegEx for this and would prefer if answers could be an implementation that does this using JavaScript's RegEx Replace function.
I am new to RegEx so please explain what you do and (if possible) link articles to where I can get further help.
Using replace() and passing the match to a function as parameter, and then Array(m.length).join("X") to generate the X's needed:
var str = "ABCDEFG[HIJKLMN]OPQRSTUVWXYZ"
str = str.replace(/\[[A-Z]*\]/g,(m)=>"["+Array(m.length-1).join("X")+"]")
console.log(str);
We could use also .* instead of [A-Z] in the regex to match any character.
About regular expressions there are thousands of resources, specifically in JavaScript, you could see Regular Expressions MDN but the best way to learn, in my opinion, is practicing, I find regex101 useful.
const str="ABCDEFG[HIJKLMN]OPQRSTUVWXYZ";
const run=str=>str.replace(/\[.*]/,(a,b,c)=>c=a.replace(/[^\[\]]/g,x=>x="X"));
console.log(run(str));
The first pattern /\[.*]/ is to select letters inside bracket [] and the second pattern /[^\[\]]/ is to replace the letters to "X"
We can observe that every individual letter you wish to match is followed by a series of zero or more non-'[' characters, until a ']' is found. This is quite simple to express in JavaScript-friendly regex:
/[A-Z](?=[^\[]*\])/g
regex101 example
(?= ) is a "positive lookahead assertion"; it peeks ahead of the current matching point, without consuming characters, to verify its contents are matched. In this case, "[^[]*]" matches exactly what I described above.
Now you can substitute each [A-Z] matched with a single 'X'.
You can use the following solution to replace a string between two square brackets:
const rxp = /\[.*?\]/g;
"ABCDEFG[HIJKLMN]OPQRSTUVWXYZ".replace(rxp, (x) => {
return x.replace(rxp, "X".repeat(x.length)-2);
});

Escape dot in a regex range

Those two regex act the same way:
var str = "43gf\\..--.65";
console.log(str.replace(/[^\d.-]/g, ""));
console.log(str.replace(/[^\d\.-]/g, ""));
In the first regex I don't escape the dot(.) while in the second regex I do(\.).
What are the differences? Why is the result the same?
The dot operator . does not need to be escaped inside of a character class [].
Because the dot is inside character class (square brackets []).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches
for the character class.
If you using JavaScript to test your Regex, try \\. instead of \..
It acts on the same way because JS remove first backslash.
On regular-expressions.info, it is stated:
Remember that the dot is not a metacharacter inside a character class,
so we do not need to escape it with a backslash.
So I guess the escaping of it is unnecessary...

How to remove periods in a string using jQuery

I have the string R.E.M. and I need to make it REM
So far, I have:
$('#request_artist').val().replace(".", "");
...but I get RE.M.
Any ideas?
The first argument to replace() is usually a regular expression.
Use the global modifier:
$('#request_artist').val().replace(/\./g, "");
replace() at MDC
You could pass a regular expression to the replace method and indicate that it should replace all occurrences like this: $('#request_artist').val().replace(/\./g, '');
The method used to replace the string is not recursive, meaning once it found a matching char or string, it stop looking. U should use a regular expression replace. $("#request_artist").val().replace(/\./g, ''); Check out Javascript replace tutorial for more info.

How to remove square brackets in string using regex?

['abc','xyz'] – this string I want turn into abc,xyz using regex in javascript. I want to replace both open close square bracket & single quote with empty string ie "".
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
str.replace(/[[\]]/g,'')
here you go
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
You probably don't even need string substitution for that. If your original string is JSON, try:
js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz
Be careful with eval, of course.
Just here to propose an alternative that I find more readable.
/\[|\]/g
JavaScript implementation:
let reg = /\[|\]/g
str.replace(reg,'')
As other people have shown, all you have to do is list the [ and ] characters, but because they are special characters you have to escape them with \.
I personally find the character group definition using [] to be confusing because it uses the same special character you're trying to replace.
Therefore using the | (OR) operator you can more easily distinguish the special characters in the regex from the literal characters being replaced.
This should work for you.
str.replace(/[[\]]/g, "");

Categories