Replace leading numbers with Javascript regex - javascript

As a follow up to this question (not by me), I need to replace leading numbers of an id with \\3n (where n is the number we're replacing).
Some examples:
"1foo" -> "\\31foo"
"1foo1" -> "\\31foo1"
"12foo" -> "\\31\\32foo"
"12fo3o4" -> "\\31\\32fo3o4"
"foo123" -> "foo123"
Below is a solution that replaces every instance of the number, but I don't know enough regex to make it stop once it hits a non-number.
function magic (str) {
return str.replace(/([0-9])/g, "\\3$1");
}
... Or is regex a bad way to go? I guess it would be easy enough to do it, just looping over each character of the string manually.

Here is a way to achieve what you need using a reverse string + look-ahead approach:
function revStr(str) {
return str.split('').reverse().join('');
}
var s = "12fo3o4";
document.write(revStr(revStr(s).replace(/\d(?=\d*$)/g, function (m) {
return m + "3\\\\";
}))
);
The regex is matching a number that can be followed by 0 or more numbers only until the end (which is actually start) of a reversed string (with \d(?=\d*$)). The callback allows to manipulate the match (we just add reversed \\ and 3. Then, we just reverse the result.

Just use two steps: first find the prefix, then operate on its characters:
s.replace(/^\d+/, function (m) {
return [].map.call(m, function (c) {
return '\\3' + c;
}).join('');
});
No need to emulate any features.

Here is how I would have done it:
function replace(str) {
var re = /^([\d]*)/;
var match = str.match(re)[0];
var replaced = match.replace(/([\d])/g, "\\3$1");
str = str.replace(match, replaced);
return str;
}
document.write(replace("12fo3o4"));
Don't get me wrong: the other answers are fine! My focus was more on readability.

Related

Removing last two characters of a string [duplicate]

I have a string, 12345.00, and I would like it to return 12345.0.
I have looked at trim, but it looks like it is only trimming whitespace and slice which I don't see how this would work. Any suggestions?
You can use the substring function:
let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";
str = str.slice(0, -1);
console.log(str);
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
js>"12345.00".slice(0,-1)
12345.0
You can use the substring method of JavaScript string objects:
s = s.substring(0, s.length - 4)
It unconditionally removes the last four characters from string s.
However, if you want to conditionally remove the last four characters, only if they are exactly _bar:
var re = /_bar$/;
s.replace(re, "");
The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):
const s = "your string";
const withoutLastFourChars = s.slice(0, -4);
If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):
const s = "your_string";
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
console.log(withoutLastChunk);
For a number like your example, I would recommend doing this over substring:
console.log(parseFloat('12345.00').toFixed(1));
Do note that this will actually round the number, though, which I would imagine is desired but maybe not:
console.log(parseFloat('12345.46').toFixed(1));
Be aware that String.prototype.{ split, slice, substr, substring } operate on UTF-16 encoded strings
None of the previous answers are Unicode-aware.
Strings are encoded as UTF-16 in most modern JavaScript engines, but higher Unicode code points require surrogate pairs, so older, pre-existing string methods operate on UTF-16 code units, not Unicode code points.
See: Do NOT use .split('').
const string = "ẞ🦊";
console.log(string.slice(0, -1)); // "ẞ\ud83e"
console.log(string.substr(0, string.length - 1)); // "ẞ\ud83e"
console.log(string.substring(0, string.length - 1)); // "ẞ\ud83e"
console.log(string.replace(/.$/, "")); // "ẞ\ud83e"
console.log(string.match(/(.*).$/)[1]); // "ẞ\ud83e"
const utf16Chars = string.split("");
utf16Chars.pop();
console.log(utf16Chars.join("")); // "ẞ\ud83e"
In addition, RegExp methods, as suggested in older answers, don’t match line breaks at the end:
const string = "Hello, world!\n";
console.log(string.replace(/.$/, "").endsWith("\n")); // true
console.log(string.match(/(.*).$/) === null); // true
Use the string iterator to iterate characters
Unicode-aware code utilizes the string’s iterator; see Array.from and ... spread.
string[Symbol.iterator] can be used (e.g. instead of string) as well.
Also see How to split Unicode string to characters in JavaScript.
Examples:
const string = "ẞ🦊";
console.log(Array.from(string).slice(0, -1).join("")); // "ẞ"
console.log([
...string
].slice(0, -1).join("")); // "ẞ"
Use the s and u flags on a RegExp
The dotAll or s flag makes . match line break characters, the unicode or u flag enables certain Unicode-related features.
Note that, when using the u flag, you eliminate unnecessary identity escapes, as these are invalid in a u regex, e.g. \[ is fine, as it would start a character class without the backslash, but \: isn’t, as it’s a : with or without the backslash, so you need to remove the backslash.
Examples:
const unicodeString = "ẞ🦊",
lineBreakString = "Hello, world!\n";
console.log(lineBreakString.replace(/.$/s, "").endsWith("\n")); // false
console.log(lineBreakString.match(/(.*).$/s) === null); // false
console.log(unicodeString.replace(/.$/su, "")); // ẞ
console.log(unicodeString.match(/(.*).$/su)[1]); // ẞ
// Now `split` can be made Unicode-aware:
const unicodeCharacterArray = unicodeString.split(/(?:)/su),
lineBreakCharacterArray = lineBreakString.split(/(?:)/su);
unicodeCharacterArray.pop();
lineBreakCharacterArray.pop();
console.log(unicodeCharacterArray.join("")); // "ẞ"
console.log(lineBreakCharacterArray.join("").endsWith("\n")); // false
Note that some graphemes consist of more than one code point, e.g. 🏳️‍🌈 which consists of the sequence 🏳 (U+1F3F3), VS16 (U+FE0F), ZWJ (U+200D), 🌈 (U+1F308).
Here, even Array.from will split this into four “characters”.
Matching those is made easier with the RegExp set notation and properties of strings proposal.
Using JavaScript's slice function:
let string = 'foo_bar';
string = string.slice(0, -4); // Slice off last four characters here
console.log(string);
This could be used to remove '_bar' at end of a string, of any length.
A regular expression is what you are looking for:
let str = "foo_bar";
console.log(str.replace(/_bar$/, ""));
Try this:
const myString = "Hello World!";
console.log(myString.slice(0, -1));
Performance
Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.
Conclusions
the slice(0,-1)(D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution
solutions based on substring (C) and substr(E) are fast
solutions based on regular expressions (A,B) are slow/medium fast
solutions B, F and G are slow for long strings
solution F is slowest for short strings, G is slowest for long strings
Details
I perform two tests for solutions A, B, C, D, E(ext), F, G(my)
for 8-char short string (from OP question) - you can run it HERE
for 1M long string - you can run it HERE
Solutions are presented in below snippet
function A(str) {
return str.replace(/.$/, '');
}
function B(str) {
return str.match(/(.*).$/)[1];
}
function C(str) {
return str.substring(0, str.length - 1);
}
function D(str) {
return str.slice(0, -1);
}
function E(str) {
return str.substr(0, str.length - 1);
}
function F(str) {
let s= str.split("");
s.pop();
return s.join("");
}
function G(str) {
let s='';
for(let i=0; i<str.length-1; i++) s+=str[i];
return s;
}
// ---------
// TEST
// ---------
let log = (f)=>console.log(`${f.name}: ${f("12345.00")}`);
[A,B,C,D,E,F,G].map(f=>log(f));
This snippet only presents soutions
Here are example results for Chrome for short string
Use regex:
let aStr = "12345.00";
aStr = aStr.replace(/.$/, '');
console.log(aStr);
How about:
let myString = "12345.00";
console.log(myString.substring(0, myString.length - 1));
1. (.*), captures any character multiple times:
console.log("a string".match(/(.*).$/)[1]);
2. ., matches last character, in this case:
console.log("a string".match(/(.*).$/));
3. $, matches the end of the string:
console.log("a string".match(/(.*).{2}$/)[1]);
https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string
Just use trim if you don't want spaces
"11.01 °C".slice(0,-2).trim()
Here is an alternative that i don't think i've seen in the other answers, just for fun.
var strArr = "hello i'm a string".split("");
strArr.pop();
document.write(strArr.join(""));
Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.
debris = string.split("_") //explode string into array of strings indexed by "_"
debris.pop(); //pop last element off the array (which you didn't want)
result = debris.join("_"); //fuse the remainng items together like the sun
If you want to do generic rounding of floats, instead of just trimming the last character:
var float1 = 12345.00,
float2 = 12345.4567,
float3 = 12345.982;
var MoreMath = {
/**
* Rounds a value to the specified number of decimals
* #param float value The value to be rounded
* #param int nrDecimals The number of decimals to round value to
* #return float value rounded to nrDecimals decimals
*/
round: function (value, nrDecimals) {
var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
return Math.round(value * x) / x;
}
}
MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0
EDIT: Seems like there exists a built in function for this, as Paolo points out. That solution is obviously much cleaner than mine. Use parseFloat followed by toFixed
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
Via slice(indexStart, indexEnd) method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.
console.clear();
let str = "12345.00";
let a = str.slice(0, str.length -1)
console.log(a, "<= a");
console.log(str, "<= str is NOT changed");
Via Regular Expression method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.
console.clear();
let regExp = /.$/g
let b = str.replace(regExp,"")
console.log(b, "<= b");
console.log(str, "<= str is NOT changed");
Via array.splice() method -> this only works on arrays, and it CHANGES, the existing array (so careful with this one), you'll need to convert a string to an array first, then back.
console.clear();
let str = "12345.00";
let strToArray = str.split("")
console.log(strToArray, "<= strToArray");
let spliceMethod = strToArray.splice(str.length-1, 1)
str = strToArray.join("")
console.log(str, "<= str is changed now");
In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().
I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:
var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";
To remove the last comma I did the following:
str = str.slice(0, -5) + str.substr(-4);
You can, in fact, remove the last arr.length - 2 items of an array using arr.length = 2, which if the array length was 5, would remove the last 3 items.
Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we've made any modifications.
var str = 'string'
String.prototype.removeLast = function(n) {
var string = this.split('')
string.length = string.length - n
return string.join('')
}
console.log(str.removeLast(3))
Try to use toFixed
const str = "12345.00";
return (+str).toFixed(1);
Try this:
<script>
var x="foo_foo_foo_bar";
for (var i=0; i<=x.length; i++) {
if (x[i]=="_" && x[i+1]=="b") {
break;
}
else {
document.write(x[i]);
}
}
</script>
You can also try the live working example on http://jsfiddle.net/informativejavascript/F7WTn/87/.
#Jason S:
You can use slice! You just have to
make sure you know how to use it.
Positive #s are relative to the
beginning, negative numbers are
relative to the end.
js>"12345.00".slice(0,-1)
12345.0
Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ...
In other words answer #Jon Erickson suggest really perfect solution.
However, your method will works out of jQuery function, inside simple Javascript.
Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.
Here also exist two methods:
as our:
string.substring(from,to) as plus if 'to' index nulled returns the rest of string. so:
string.substring(from) positive or negative ...
and some other - substr() - which provide range of substring and 'length' can be positive only:
string.substr(start,length)
Also some maintainers suggest that last method string.substr(start,length) do not works or work with error for MSIE.
Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:
str.substring(3, 7);
3 is that start and 7 is the length.

Javascript convert PascalCase to underscore_case/snake_case

How can I convert PascalCase string into underscore_case/snake_case string? I need to convert dots into underscores as well.
eg. convert
TypeOfData.AlphaBeta
into
type_of_data_alpha_beta
You could try the below steps.
Capture all the uppercase letters and also match the preceding optional dot character.
Then convert the captured uppercase letters to lowercase and then return back to replace function with an _ as preceding character. This will be achieved by using anonymous function in the replacement part.
This would replace the starting uppercase letter to _ + lowercase_letter.
Finally removing the starting underscore will give you the desired output.
var s = 'TypeOfData.AlphaBeta';
console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
OR
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
any way to stop it for when a whole word is in uppercase. eg. MotorRPM into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a?
var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
str.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
u're welcome
var s1 = 'someTextHere';
var s2 = 'SomeTextHere';
var s3 = 'TypeOfData.AlphaBeta';
var o1 = s1.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o2 = s2.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o3 = s3.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
console.log(o1);
console.log(o2);
console.log(o3);
Alternatively using lodash:
lodash.snakeCase(str);
Example:
_.snakeCase('TypeOfData.AlphaBeta');
// ➜ 'type_of_data_alpha_beta'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.
This solution solves the non-trailing acronym issue with the solutions above
I ported the code in 1175208 from Python to JavaScript.
Javascript Code
function camelToSnakeCase(text) {
return text.replace(/(.)([A-Z][a-z]+)/, '$1_$2').replace(/([a-z0-9])([A-Z])/, '$1_$2').toLowerCase()
}
Working Examples:
camelToSnakeCase('thisISDifficult') -> this_is_difficult
camelToSnakeCase('thisISNT') -> this_isnt
camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this
"alphaBetaGama".replace(/([A-Z])/g, "_$1").toLowerCase() // alpha_beta_gamma
Problem - Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.
Explanation
This line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).
Each match in the string is converted to have an underscore ahead of it with _$1 string provided. At that point the string looks like alpha_Beta_Gamma.
To correct the capitalization, the entire string is converted toLowerCase().
Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.
After toLowerCase it the resulting string is alpha_beta_gamma ( in this example )
This will get you pretty far: https://github.com/domchristie/humps
You will probably have to use regex replace to replace the "." with an underscore.
I found this but I edited it so suit your question.
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/,'')
Good examples for js:
Snake Case
Kebab Case
Camel Case
Pascal Case
have here
function toCamelCase(s) {
// remove all characters that should not be in a variable name
// as well underscores an numbers from the beginning of the string
s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase();
// uppercase letters preceeded by a hyphen or a space
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) {
return c.toUpperCase();
});
// uppercase letters following numbers
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b + c.toUpperCase();
});
return s;
}
Try this function, hope it helps.
"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"")
replaces all uppercase with an underscore and lowercase, then removes the leading underscore.
A Non-Regex Answer that converts PascalCase to snake_case
Note: I understand there are tons of good answers which solve this question elegantly. I was recently working on something similar to this where I chose not to use regex. So I felt to answer a non-regex solution to this.
const toSnakeCase = (str) => {
return str.slice(0,1).toLowerCase() + str.split('').slice(1).map((char) => {
if (char == char.toUpperCase()) return '_' + char.toLowerCase();
else return char;
}).join('');
}
Eg.
inputString = "ILoveJavascript" passed onto toSnakeCase()
would become "i_love_javascript"

How to use Javascript to change link [duplicate]

I've got a data-123 string.
How can I remove data- from the string while leaving the 123?
var ret = "data-123".replace('data-','');
console.log(ret); //prints: 123
Docs.
For all occurrences to be discarded use:
var ret = "data-123".replace(/data-/g,'');
PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.
This doesn't have anything to do with jQuery. You can use the JavaScript replace function for this:
var str = "data-123";
str = str.replace("data-", "");
You can also pass a regex to this function. In the following example, it would replace everything except numerics:
str = str.replace(/[^0-9\.]+/g, "");
You can use "data-123".replace('data-','');, as mentioned, but as replace() only replaces the FIRST instance of the matching text, if your string was something like "data-123data-" then
"data-123data-".replace('data-','');
will only replace the first matching text. And your output will be "123data-"
DEMO
So if you want all matches of text to be replaced in string you have to use a regular expression with the g flag like that:
"data-123data-".replace(/data-/g,'');
And your output will be "123"
DEMO2
You can use slice(), if you will know in advance how many characters need slicing off the original string. It returns characters between a given start point to an end point.
string.slice(start, end);
Here are some examples showing how it works:
var mystr = ("data-123").slice(5); // This just defines a start point so the output is "123"
var mystr = ("data-123").slice(5,7); // This defines a start and an end so the output is "12"
Demo
Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:
var myString = "data-123";
var myNewString = myString.replace("data-", "");
See: .replace() docs on MDN for additional information and usage.
1- If is the sequences into your string:
let myString = "mytest-text";
let myNewString = myString.replace("mytest-", "");
the answer is text
2- if you whant to remove the first 3 characters:
"mytest-text".substring(3);
the answer is est-text
Ex:-
var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);
Hopefully this will work for you.
Performance
Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.
Results
For all browsers
solutions Ba, Cb, and Db are fast/fastest for long strings
solutions Ca, Da are fast/fastest for short strings
solutions Ab and E are slow for long strings
solutions Ba, Bb and F are slow for short strings
Details
I perform 2 tests cases:
short string - 10 chars - you can run it HERE
long string - 1 000 000 chars - you can run it HERE
Below snippet presents solutions
Aa
Ab
Ba
Bb
Ca
Cb
Da
Db
E
F
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string
// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
return str.replace(strToRemove,'');
}
// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
return str.replaceAll(strToRemove,'');
}
// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replace(new RegExp(re),'');
}
// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replaceAll(new RegExp(re,'g'),'');
}
// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
let start = str.search(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
let start = str.search(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
return str.split(strToRemove).join('');
}
// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
var n = str.search(strToRemove);
while (str.search(strToRemove) > -1) {
n = str.search(strToRemove);
str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
}
return str;
}
let str = "data-123";
let strToRemove = "data-";
[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
This little function I made has always worked for me :)
String.prototype.deleteWord = function (searchTerm) {
var str = this;
var n = str.search(searchTerm);
while (str.search(searchTerm) > -1) {
n = str.search(searchTerm);
str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
}
return str;
}
// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!
I know it is not the best, but It has always worked for me :)
str.split('Yes').join('No');
This will replace all the occurrences of that specific string from original string.
I was used to the C# (Sharp) String.Remove method.
In Javascript, there is no remove function for string, but there is substr function.
You can use the substr function once or twice to remove characters from string.
You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("data-123", 0, 5));
Output: 123
Using match() and Number() to return a number variable:
Number(("data-123").match(/\d+$/));
// strNum = 123
Here's what the statement above does...working middle-out:
str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.
Update 2023
There are many ways to solve this problem, but I believe this is the simplest:
const newString = string.split("data-").pop();
console.log(newString); /// 123
For doing such a thing there are a lot of different ways. A further way could be the following:
let str = 'data-123';
str = str.split('-')[1];
console.log('The remaining string is:\n' + str);
Basically the above code splits the string at the '-' char into two array elements and gets the second one, that is the one with the index 1, ignoring the first array element at the 0 index.
The following is one liner version:
console.log('The remaining string is:\n' + 'data-123'.split('-')[1]);
Another possible approach would be to add a method to the String prototype as follows:
String.prototype.remove = function (s){return this.replace(s,'')}
// After that it will be used like this:
a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.remove('k');
console.log(a);
Notice the above snippet will allow to remove only the first instance of the string you are interested to remove. But you can improve it a bit as follows:
String.prototype.removeAll = function (s){return this.replaceAll(s,'')}
// After that it will be used like this:
a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.removeAll('k');
console.log(a);
The above snippet instead will remove all instances of the string passed to the method.
Of course you don't need to implement the functions into the prototype of the String object: you can implement them as simple functions too if you wish (I will show the remove all function, for the other you will need to use just replace instead of replaceAll, so it is trivial to implement):
function strRemoveAll(s,r)
{
return s.replaceAll(r,'');
}
// you can use it as:
let a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk'
b = strRemoveAll (a,'k');
console.log(b);
Of course much more is possible.
Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll() method.
It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.
As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE. For mobile, iOS SafariiOS 13.7+, Android Chromev85+, and Android Firefoxv79+ are all supported as well.
* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+
It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.
References:
MDN
Can I Use - Current Browser Support Information
TC39 Proposal Repo for .replaceAll()
You can test your current browser in the snippet below:
//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi;
try {
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
console.log('Your browser is supported!');
} catch (e) {
console.log('Your browser is unsupported! :(');
}
.as-console-wrapper: {
max-height: 100% !important;
}
Make sure that if you are replacing strings in a loop that you initiate a new Regex in each iteration. As of 9/21/21, this is still a known issue with Regex essentially missing every other match. This threw me for a loop when I encountered this the first time:
yourArray.forEach((string) => {
string.replace(new RegExp(__your_regex__), '___desired_replacement_value___');
})
If you try and do it like so, don't be surprised if only every other one works
let reg = new RegExp('your regex');
yourArray.forEach((string) => {
string.replace(reg, '___desired_replacement_value___');
})

trim certain number of characters from end of javascript string [duplicate]

I have a string, 12345.00, and I would like it to return 12345.0.
I have looked at trim, but it looks like it is only trimming whitespace and slice which I don't see how this would work. Any suggestions?
You can use the substring function:
let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";
str = str.slice(0, -1);
console.log(str);
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
js>"12345.00".slice(0,-1)
12345.0
You can use the substring method of JavaScript string objects:
s = s.substring(0, s.length - 4)
It unconditionally removes the last four characters from string s.
However, if you want to conditionally remove the last four characters, only if they are exactly _bar:
var re = /_bar$/;
s.replace(re, "");
The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):
const s = "your string";
const withoutLastFourChars = s.slice(0, -4);
If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):
const s = "your_string";
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
console.log(withoutLastChunk);
For a number like your example, I would recommend doing this over substring:
console.log(parseFloat('12345.00').toFixed(1));
Do note that this will actually round the number, though, which I would imagine is desired but maybe not:
console.log(parseFloat('12345.46').toFixed(1));
Be aware that String.prototype.{ split, slice, substr, substring } operate on UTF-16 encoded strings
None of the previous answers are Unicode-aware.
Strings are encoded as UTF-16 in most modern JavaScript engines, but higher Unicode code points require surrogate pairs, so older, pre-existing string methods operate on UTF-16 code units, not Unicode code points.
See: Do NOT use .split('').
const string = "ẞ🦊";
console.log(string.slice(0, -1)); // "ẞ\ud83e"
console.log(string.substr(0, string.length - 1)); // "ẞ\ud83e"
console.log(string.substring(0, string.length - 1)); // "ẞ\ud83e"
console.log(string.replace(/.$/, "")); // "ẞ\ud83e"
console.log(string.match(/(.*).$/)[1]); // "ẞ\ud83e"
const utf16Chars = string.split("");
utf16Chars.pop();
console.log(utf16Chars.join("")); // "ẞ\ud83e"
In addition, RegExp methods, as suggested in older answers, don’t match line breaks at the end:
const string = "Hello, world!\n";
console.log(string.replace(/.$/, "").endsWith("\n")); // true
console.log(string.match(/(.*).$/) === null); // true
Use the string iterator to iterate characters
Unicode-aware code utilizes the string’s iterator; see Array.from and ... spread.
string[Symbol.iterator] can be used (e.g. instead of string) as well.
Also see How to split Unicode string to characters in JavaScript.
Examples:
const string = "ẞ🦊";
console.log(Array.from(string).slice(0, -1).join("")); // "ẞ"
console.log([
...string
].slice(0, -1).join("")); // "ẞ"
Use the s and u flags on a RegExp
The dotAll or s flag makes . match line break characters, the unicode or u flag enables certain Unicode-related features.
Note that, when using the u flag, you eliminate unnecessary identity escapes, as these are invalid in a u regex, e.g. \[ is fine, as it would start a character class without the backslash, but \: isn’t, as it’s a : with or without the backslash, so you need to remove the backslash.
Examples:
const unicodeString = "ẞ🦊",
lineBreakString = "Hello, world!\n";
console.log(lineBreakString.replace(/.$/s, "").endsWith("\n")); // false
console.log(lineBreakString.match(/(.*).$/s) === null); // false
console.log(unicodeString.replace(/.$/su, "")); // ẞ
console.log(unicodeString.match(/(.*).$/su)[1]); // ẞ
// Now `split` can be made Unicode-aware:
const unicodeCharacterArray = unicodeString.split(/(?:)/su),
lineBreakCharacterArray = lineBreakString.split(/(?:)/su);
unicodeCharacterArray.pop();
lineBreakCharacterArray.pop();
console.log(unicodeCharacterArray.join("")); // "ẞ"
console.log(lineBreakCharacterArray.join("").endsWith("\n")); // false
Note that some graphemes consist of more than one code point, e.g. 🏳️‍🌈 which consists of the sequence 🏳 (U+1F3F3), VS16 (U+FE0F), ZWJ (U+200D), 🌈 (U+1F308).
Here, even Array.from will split this into four “characters”.
Matching those is made easier with the RegExp set notation and properties of strings proposal.
Using JavaScript's slice function:
let string = 'foo_bar';
string = string.slice(0, -4); // Slice off last four characters here
console.log(string);
This could be used to remove '_bar' at end of a string, of any length.
A regular expression is what you are looking for:
let str = "foo_bar";
console.log(str.replace(/_bar$/, ""));
Try this:
const myString = "Hello World!";
console.log(myString.slice(0, -1));
Performance
Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.
Conclusions
the slice(0,-1)(D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution
solutions based on substring (C) and substr(E) are fast
solutions based on regular expressions (A,B) are slow/medium fast
solutions B, F and G are slow for long strings
solution F is slowest for short strings, G is slowest for long strings
Details
I perform two tests for solutions A, B, C, D, E(ext), F, G(my)
for 8-char short string (from OP question) - you can run it HERE
for 1M long string - you can run it HERE
Solutions are presented in below snippet
function A(str) {
return str.replace(/.$/, '');
}
function B(str) {
return str.match(/(.*).$/)[1];
}
function C(str) {
return str.substring(0, str.length - 1);
}
function D(str) {
return str.slice(0, -1);
}
function E(str) {
return str.substr(0, str.length - 1);
}
function F(str) {
let s= str.split("");
s.pop();
return s.join("");
}
function G(str) {
let s='';
for(let i=0; i<str.length-1; i++) s+=str[i];
return s;
}
// ---------
// TEST
// ---------
let log = (f)=>console.log(`${f.name}: ${f("12345.00")}`);
[A,B,C,D,E,F,G].map(f=>log(f));
This snippet only presents soutions
Here are example results for Chrome for short string
Use regex:
let aStr = "12345.00";
aStr = aStr.replace(/.$/, '');
console.log(aStr);
How about:
let myString = "12345.00";
console.log(myString.substring(0, myString.length - 1));
1. (.*), captures any character multiple times:
console.log("a string".match(/(.*).$/)[1]);
2. ., matches last character, in this case:
console.log("a string".match(/(.*).$/));
3. $, matches the end of the string:
console.log("a string".match(/(.*).{2}$/)[1]);
https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string
Just use trim if you don't want spaces
"11.01 °C".slice(0,-2).trim()
Here is an alternative that i don't think i've seen in the other answers, just for fun.
var strArr = "hello i'm a string".split("");
strArr.pop();
document.write(strArr.join(""));
Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.
debris = string.split("_") //explode string into array of strings indexed by "_"
debris.pop(); //pop last element off the array (which you didn't want)
result = debris.join("_"); //fuse the remainng items together like the sun
If you want to do generic rounding of floats, instead of just trimming the last character:
var float1 = 12345.00,
float2 = 12345.4567,
float3 = 12345.982;
var MoreMath = {
/**
* Rounds a value to the specified number of decimals
* #param float value The value to be rounded
* #param int nrDecimals The number of decimals to round value to
* #return float value rounded to nrDecimals decimals
*/
round: function (value, nrDecimals) {
var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
return Math.round(value * x) / x;
}
}
MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0
EDIT: Seems like there exists a built in function for this, as Paolo points out. That solution is obviously much cleaner than mine. Use parseFloat followed by toFixed
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
Via slice(indexStart, indexEnd) method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.
console.clear();
let str = "12345.00";
let a = str.slice(0, str.length -1)
console.log(a, "<= a");
console.log(str, "<= str is NOT changed");
Via Regular Expression method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.
console.clear();
let regExp = /.$/g
let b = str.replace(regExp,"")
console.log(b, "<= b");
console.log(str, "<= str is NOT changed");
Via array.splice() method -> this only works on arrays, and it CHANGES, the existing array (so careful with this one), you'll need to convert a string to an array first, then back.
console.clear();
let str = "12345.00";
let strToArray = str.split("")
console.log(strToArray, "<= strToArray");
let spliceMethod = strToArray.splice(str.length-1, 1)
str = strToArray.join("")
console.log(str, "<= str is changed now");
In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().
I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:
var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";
To remove the last comma I did the following:
str = str.slice(0, -5) + str.substr(-4);
You can, in fact, remove the last arr.length - 2 items of an array using arr.length = 2, which if the array length was 5, would remove the last 3 items.
Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we've made any modifications.
var str = 'string'
String.prototype.removeLast = function(n) {
var string = this.split('')
string.length = string.length - n
return string.join('')
}
console.log(str.removeLast(3))
Try to use toFixed
const str = "12345.00";
return (+str).toFixed(1);
Try this:
<script>
var x="foo_foo_foo_bar";
for (var i=0; i<=x.length; i++) {
if (x[i]=="_" && x[i+1]=="b") {
break;
}
else {
document.write(x[i]);
}
}
</script>
You can also try the live working example on http://jsfiddle.net/informativejavascript/F7WTn/87/.
#Jason S:
You can use slice! You just have to
make sure you know how to use it.
Positive #s are relative to the
beginning, negative numbers are
relative to the end.
js>"12345.00".slice(0,-1)
12345.0
Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ...
In other words answer #Jon Erickson suggest really perfect solution.
However, your method will works out of jQuery function, inside simple Javascript.
Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.
Here also exist two methods:
as our:
string.substring(from,to) as plus if 'to' index nulled returns the rest of string. so:
string.substring(from) positive or negative ...
and some other - substr() - which provide range of substring and 'length' can be positive only:
string.substr(start,length)
Also some maintainers suggest that last method string.substr(start,length) do not works or work with error for MSIE.
Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:
str.substring(3, 7);
3 is that start and 7 is the length.

How can I remove a character from a string using JavaScript?

I am so close to getting this, but it just isn't right.
All I would like to do is remove the character r from a string.
The problem is, there is more than one instance of r in the string.
However, it is always the character at index 4 (so the 5th character).
Example string: crt/r2002_2
What I want: crt/2002_2
This replace function removes both r
mystring.replace(/r/g, '')
Produces: ct/2002_2
I tried this function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')
It only works if I replace it with another character. It will not simply remove it.
Any thoughts?
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');
will replace /r with / using String.prototype.replace.
Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with
mystring = mystring.replace(/\/r/g, '/');
EDIT:
Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:
String.prototype.removeCharAt = function (i) {
var tmp = this.split(''); // convert to an array
tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
return tmp.join(''); // reconstruct the string
}
console.log("crt/r2002_2".removeCharAt(4));
Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.
A simple functional javascript way would be
mystring = mystring.split('/r').join('/')
simple, fast, it replace globally and no need for functions or prototypes
There's always the string functions, if you know you're always going to remove the fourth character:
str.slice(0, 4) + str.slice(5, str.length)
Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.
Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:
mystring.replace(/\/r/, '/')
Now for the excessive explanation:
When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...
In regEx <a character or set of charcters> could be one at a time:
/each char in this pattern/
So read as e, followed by a, followed by c, etc...
Or a single <a character or set of charcters> could be characters described by a character class:
/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)
Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):
/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would
/[aA]{1,3}/
//1-3 matches of 'a' or 'A'
/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class
/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)
So smoosh a bunch together:
var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can eat098765';
joesStr.match(rePattern);
//returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
//without the 'g' after the closing '/' it would just stop at the first match and return:
//["aaaAAAaaEat at Joes123454321"]
And of course I've over-elaborated but my point was simply that this:
/cat/
is a series of 3 pattern elements (a thing followed by a thing followed by a thing).
And so is this:
/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/
As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.
Just fix your replaceAt:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
mystring.replaceAt(4, 1);
I'd call it removeAt instead. :)
For global replacement of '/r', this code worked for me.
mystring = mystring.replace(/\/r/g,'');
This is improvement of simpleigh answer (omit length)
s.slice(0, 4) + s.slice(5)
let s = "crt/r2002_2";
let o = s.slice(0, 4) + s.slice(5);
let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1); // this function remove letter at index i
console.log(o);
console.log(delAtIdx(s, 4));
let str = '1234567';
let index = 3;
str = str.substring(0, index) + str.substring(index + 1);
console.log(str) // 123567 - number "4" under index "3" is removed
return this.substr(0, index) + char + this.substr(index + char.length);
char.length is zero. You need to add 1 in this case in order to skip character.
Maybe I'm a noob, but I came across these today and they all seem unnecessarily complicated.
Here's a simpler (to me) approach to removing whatever you want from a string.
function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']
for (let char of forbiddenChars){
input = input.split(char).join('');
}
return input
}
Create function like below
String.prototype.replaceAt = function (index, char) {
if(char=='') {
return this.slice(0,index)+this.substr(index+1 + char.length);
} else {
return this.substr(0, index) + char + this.substr(index + char.length);
}
}
To replace give character like below
var a="12346";
a.replaceAt(4,'5');
and to remove character at definite index, give second parameter as empty string
a.replaceAt(4,'');
If it is always the 4th char in yourString you can try:
yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });
It only works if I replace it with another character. It will not simply remove it.
This is because when char is equal to "", char.length is 0, so your substrings combine to form the original string. Going with your code attempt, the following will work:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + 1);
// this will 'replace' the character at index with char ^
}
DEMO
You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)
Explanation:
if ( str[4] === 'r' )
Check if the 5th character is a 'r'
str.slice(0, 4)
Slice the string to get everything before the 'r'
+ str.slice(5)
Add the rest of the string.
Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]
DEMO:
function remove5thR (s) {
s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
console.log(s); // log output
}
remove5thR('crt/r2002_2') // > 'crt/2002_2'
remove5thR('crt|r2002_2') // > 'crt|2002_2'
remove5thR('rrrrr') // > 'rrrr'
remove5thR('RRRRR') // > 'RRRRR' (no change)
If you just want to remove single character and
If you know index of a character you want to remove, you can use following function:
/**
* Remove single character at particular index from string
* #param {*} index index of character you want to remove
* #param {*} str string from which character should be removed
*/
function removeCharAtIndex(index, str) {
var maxIndex=index==0?0:index;
return str.substring(0, maxIndex) + str.substring(index, str.length)
}
I dislike using replace function to remove characters from string. This is not logical to do it like that. Usually I program in C# (Sharp), and whenever I want to remove characters from string, I use the Remove method of the String class, but no Replace method, even though it exists, because when I am about to remove, I remove, no replace. This is logical!
In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("crt/r2002_2", 4, 1));
Output: crt/2002_2
Achieving goals by doing techniques with no logic might cause confusions in understanding of the code, and future mistakes, if you do this a lot in a large project!
The following function worked best for my case:
public static cut(value: string, cutStart: number, cutEnd: number): string {
return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
The shortest way would be to use splice
var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);
This problem has many applications. Tweaking #simpleigh solution to make it more copy/paste friendly:
function removeAt( str1, idx) {
return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1)) // prints: abcdef
Using [index] position for removing a specific char (s)
String.prototype.remplaceAt = function (index, distance) {
return this.slice(0, index) + this.slice(index + distance, this.length);
};
credit to https://stackoverflow.com/users/62576/ken-white
So basically, another way would be to:
Convert the string to an array using Array.from() method.
Loop through the array and delete all r letters except for the one with index 1.
Convert array back to a string.
let arr = Array.from("crt/r2002_2");
arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });
document.write(arr.join(""));
In C# (Sharp), you can make an empty character as '\0'.
Maybe you can do this:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')
Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!
Finally that 'r' character will be removed!

Categories