Remove dot . sign from the end of the string - javascript

I have this requirement where it is required to remove only the last . dot sign from a string.
Say if we have var str = 'abcd dhfjd.fhfjd.'; i need remove the final dot sign which would output abcd dhfjd.fhfjd .
I found this link ( Javascript function to remove leading dot ) which removes the first dot sign but I am new to this whole thing and could not find any source on how to remove a specific last character if exists.
Thank you :)

Single dot:
if (str[str.length-1] === ".")
str = str.slice(0,-1);
Multiple dots:
while (str[str.length-1] === ".")
str = str.slice(0,-1);
Single dot, regex:
str = str.replace(/\.$/, "");
Multiple dots, regex:
str = str.replace(/\.+$/, "");

if(str.lastIndexOf('.') === (str.length - 1)){
str = str.substring(0, str.length - 1);
}

This will remove all trailing dots, and may be easier to understand for a beginner (compared to the other answers):
while(str.charAt(str.length-1) == '.')
{
str = str.substr(0, str.length-1);
}

Related

Is there a regex to replace all occurences except for the first one?

I already tried to use this for above mentioned intention
var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d(,.)?]/g, '');
console.log(str);
I expected the output would be 485,225
because of the 0-1 condition through the question mark.
However my output is 485,225.,87
Simply my final approach is to have a number seperated by comma or a dot.
Following pattern would fit my intention:
{1-9}+{0-9)?{, | . }{1-9}*
Would love to hear your solutions.
Inside character classes, all chars are literal, except for ^, \, [ and -. So, you cannot add ? there and expect it to behave as a quantifier.
You need
var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d,.]+/g, '').replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1').replace(/^0+/, "");
console.log(str);
The .replace(/[^\d,.]+/g, '') part removes all chars other than digits, dots and commas.
The .replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1') part keeps the first steak of digits and optionally a second streak of digits after the first . or ,.
The .replace(/^0+/, "") part removes one or more 0 digits at the beginning of the string.
Your fixed demo fiddle:
function testRegex(event){
let evt = event || window.event
console.log(evt.target.value)
document.getElementById("result").innerHTML = "Result: "+
evt.target.value.replace(/[^\d,.]+/g, '')
.replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1')
.replace(/^0+/, "");
}
<label>Value:</label>
<input onkeyup="testRegex()" type="text"/>
<p id="result">Result:</p>

Javascript regular expression to reduce 'n' same consecutive characters to single character in a given string

Ex:
var str = "......43.....DF.67....89...........";
while(str.search(/(..)/g) > -1) {
str = str.replace(/(..)/g, '.');
}
str = str.replace('.', '-');
Output: -43-DF-67-89-
Steps 01: I am replacing two '.' (i.e., '..') to one '.' using regular expression.
Steps 02: If no more two '.', then finally I am replacing one '.' with '-'
But I need to achieve in one step without loops.
You can escape the period and use the + operator to indicate one or more periods.
var str = "......43.....DF.67....89...........";
str = str.replace(/\.+/g, '-');
console.log(str);

javascript remove all succeeding occurrence of a character in string

I'm aiming to remove a succeeding occurrence of 2 particular characters from a string: the dot and the negative sign. let's say we have -123-456.78.9.0-12, I should be getting -123456.789012 afterwards. can it be done via regex replace?
If I may add, my complete goal is to just allow numbers, negative sign, and dot, with the negative sign only being allowed either as the first character or not present at all.
thanks so much
You can do this in 3 replace calls:
function repl(n) {
return n.replace(/[^\d.-]+/g, '') // remove all non-digits except - and .
.replace(/^([^.]*\.)|\./g, '$1') // remove all dots except first one
.replace(/(?!^)-/g, '') // remove all hyphens except first one
}
console.log(repl('-123-456.78.9.0-12'))
//=> "-123456.789012"
console.log(repl('-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
console.log(repl('-1234'))
//=> "-1234"
console.log(repl('#-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
Here:
First replace method is replacing every non-digit character except - and .
Second replace method is replacing every dot except the first one.
Third replace method is replacing every hyphen except the first hyphen.
If you want to avoid using RegExps, you can do something like this:
let str = '-123-456.78.9.0-12';
let output = '';
if (str[0] == '-') output += '-';
let periodIdx = str.indexOf('.');
for (let idx = 0; idx < str.length; idx += 1) {
let char = str.charCodeAt(idx);
if (char > 47 && char < 58) output += str[idx];
if (idx == periodIdx) output += '.';
}
console.log(output);
If I may add, my complete goal is to just allow numbers, negative sign, and dot, with the negative sign only being allowed either as the first character or not present at all.
^-?[^.-]*\.?[^.-]*$

Replace last character of string using JavaScript

I have a very small query. I tried using concat, charAt, slice and whatnot but I didn't get how to do it.
Here is my string:
var str1 = "Notion,Data,Identity,"
I want to replace the last , with a . it should look like this.
var str1 = "Notion,Data,Identity."
Can someone let me know how to achieve this?
You can do it with regex easily,
var str1 = "Notion,Data,Identity,".replace(/.$/,".")
.$ will match any character at the end of a string.
You can remove the last N characters of a string by using .slice(0, -N), and concatenate the new ending with +.
var str1 = "Notion,Data,Identity,";
var str2 = str1.slice(0, -1) + '.';
console.log(str2);
Notion,Data,Identity.
Negative arguments to slice represents offsets from the end of the string, instead of the beginning, so in this case we're asking for the slice of the string from the beginning to one-character-from-the-end.
This isn't elegant but it's reusable.
term(str, char)
str: string needing proper termination
char: character to terminate string with
var str1 = "Notion,Data,Identity,";
function term(str, char) {
var xStr = str.substring(0, str.length - 1);
return xStr + char;
}
console.log(term(str1,'.'))
You can use simple regular expression
var str1 = "Notion,Data,Identity,"
str1.replace(/,$/,".")

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

Categories

Resources