Capitalize the first letter of every word - javascript

I want to use a javascript function to capitalize the first letter of every word
eg:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test
What would be a simple javascript function

Here's a little one liner that I'm using to get the job done
var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });
but John Resig did a pretty awesome script that handles a lot of cases
http://ejohn.org/blog/title-capitalization-in-javascript/
Update
ES6+ answer:
str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
There's probably an even better way than this. It will work on accented characters.

function capitalizeEachWord(str)
{
var words = str.split(" ");
var arr = [];
for (i in words)
{
temp = words[i].toLowerCase();
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
arr.push(temp);
}
return arr.join(" ");
}

"tHiS iS a tESt".replace(/[^\s]+/g, function(str){
return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
});
Other variant:
"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){
return $1.toUpperCase()+$2.toLowerCase();
});

This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.
function capitalize(str){
var strArr = str.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1);
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}

take a look at ucwords from php.js - this seems to be kind of what you're looking for. basically, it's:
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
note that THIS IS A TEST will return THIS IS A TEST so you'll have to use it like this:
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());
or modify the function a bit:
function ucwords (str) {
str = (str + '').toLowerCase();
return str.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test

This will capitalize every word seperated by a space or a dash
function capitalize(str){
str = str.toLowerCase();
return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}
Examples :
i lOvE oRanges => I Love Oranges
a strAnge-looKing syntax => A Strange-Looking Syntax
etc

If you don't mind using a library, you could use Sugar.js capitalize()
capitalize( all = false ) Capitalizes the first character in the
string and downcases all other letters. If all is true, all words in
the string will be capitalized.
Example:
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

you can also use below approach using filter:
function Ucwords(str){
var words = str.split(' ');
var arr = [];
words.filter(function(val){
arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());
})
console.log(arr.join(" ").trim());
return arr.join(" ").trim();
}
Ucwords("THIS IS A TEST") //This Is A Test
Ucwords("THIS ") //This

{
String s = "this is for testing";
String sw[] = s.split("\\s");
String newS = "";
for(int i=0; i<=sw.length-1; i++)
{
String first = sw[i].substring(0,1);
String last = sw[i].substring(1);
newS+= first.toUpperCase()+last+" ";
}
System.out.println(newS);
}

Related

What's wrong with my code? first letter of each word should capitalized

function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2;
for(var i = 0; i < str1.length; i++){
str2 = str1[i].toLowerCase().replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
What's wrong with my code? str2.join is not a function
Easiest way to go about this is to split the string on every space, then set the first letter of each element in the array to the capitalized version of the letter and join it back.
What you are doing is assigning the value of the result to str2, having a string type rather than an array, that is why join is not working for you.
function titleCase(str) {
const words = str.split(' ');
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(' ');
}
A slightly different variant with some ES6 favor to it:
const titleCase = str => {
const result = [];
for (const word of str.split(' ')) {
result.push(word[0].toUpperCase() + word.slice(1));
}
return result.join(' ');
};
If you want to ensure space characters such as tabs, newlines etc. work, you can split using your regex or replace all whitespace characters with spaces as a first step, e.g.:
const words = str.replace(/\s/g, ' ').split(' ').filter(word => word !== '');
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2 = [];
for(var i = 0; i < str1.length; i++){
str2[i] = str1[i].replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
This is a simple solution to your problem. However, there are many ways to get the same result this is one of them.
function capitalize(str) {
let str2 = str[0].toUpperCase();
return str.replace(str[0], str2);
}

Detect Specific Words on string

Here is my String:
var str1 = '#hello, world how are you. I #am good';
Now I want to split # prefixed worlds like #hello, #am etc to be stored in an array.
Desired output will be
var str2 = [#hello, #am];
can anyone guide me.
With a simple regex
\B#\w+/g
without a function :
var str1 = '#hello, world how are you. I #am good';
console.log(str1.match(/\B#\w+/g));
with a function :
getMatchedStrings("#hello, #world how are you. I #am good");
function getMatchedStrings(input){
var re = /\B#\w+/g;
var specials = [];
var match;
while(match = re.exec(input)){
specials.push(match[0]);
}
console.log(specials)
}
You may try more regex here :
https://regex101.com/r/rBuMrY/1
Output:
["#hello", "#am"]
Check this out, i add comment for easy understand this code
var str = '#hello, world how are you. I #am good';
str = str.split(' '); // split text to word array
str = str.filter(function(word){
return word.includes('#'); // check words that using #
}).map(function (word) {
return word.replace(/[^a-zA-Z^# ]/g, "") // remove special character except #
});
console.log(str) // show the data
var str1 = '#hello, world how are you. I #am good';
var reg = /(?:^|[ ])#([a-zA-Z]+)/;
var str = str1.split(" ");
//console.log(str.length);
for (var i = 0; i < str.length; i++) {
if (reg.test(str[i])) {
//your code to store match value in another array
console.log(str[i]);
}
}
Use Regex, I am not really good at it but just a try
var str1 = '#hello, world how are you. I #am good';
var str2 = str1.match(/#(.+?)[^a-zA-Z0-9]/g).map(function(match) { return match.slice(0, -1); });
console.log(str2);

Capitalize the first letter of each string [duplicate]

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 5 years ago.
I've been trying to capitalize the first letter of each word in a string, but it says TypeError: Cannot assign to read only property '0' of string 'i' . My logic looks fine but surely the way I'm doing this is not right. Any suggestions.
function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
// console.log(word[0][0]);
for (var i = 0; i < word.length - 1; i++) {
word[i][0] = word[i][0].toUpperCase();
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");
Try like so: (see comments in code)
function titleCase(str) {
str=str.toLowerCase();
var word = str.split(" ");
for (var i=0; i < word.length; i++) { // you don't need -1 here as you had
word[i] = word[i].charAt(0).toUpperCase() + word[i].slice(1); // see changes in this line
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");
Strings have a replace method that accepts a function:
var s = 'foo bar fum i am sparticus 23!!';
console.log(s.replace(/\b\w/g, function(s){return s.toUpperCase()}));
You can directly convert your string into what you want by inbuilt array function.
Using map function you will get it directly no need to run for loop.
("I'm a little tea pot")
.split(" ")
.map(function(d){
return d[0].toUpperCase()+d.substring(1,d.length)
}).join(" ")
You can combine split and map functions to achieve this.
function titleCase(str) {
return str.toLowerCase().split(" ").map(function(word) {
var _word = word.split("");
_word[0] = _word[0].toUpperCase();
return _word.join("");
}).join(" ");
}
console.log(titleCase("I'm a little tea pot"));
You can use map function to create an array of modified words and join to recreate the string
function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
var x = word.map(function(item) {
return item.charAt(0).toUpperCase() + item.substring(1, item.length);
}).join(" ");
return x
}
console.log(titleCase("I'm a little tea pot"));
Using only CSS
#test {
text-transform: capitalize
}
<div id="test"> I'm a little tea pot</div>
With split, array map and reduce:
var str = "I'm a little tea pot";
var res = str.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.substr(1))
.reduce((m, o) => { m = m + " " + o; return m }, "")
console.log(res);
Join can be also used instead of reduce:
var str = "I'm a little tea pot";
var res = str.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.substr(1))
.join(" ");
console.log(res);

The mission is to turn each word's first letter into capital (Javascript)

The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}

How do I replace a character at a particular index in JavaScript?

I have a string, let's say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?
var str = "hello world";
I need something like
str.replaceAt(0,"h");
In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.
You'll need to define the replaceAt() function yourself:
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
And use it like this:
var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World
There is no replaceAt function in JavaScript. You can use the following code to replace any character in any string at specified position:
function rep() {
var str = 'Hello World';
str = setCharAt(str,4,'a');
alert(str);
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
<button onclick="rep();">click</button>
You can't. Take the characters before and after the position and concat into a new string:
var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);
str = str.split('');
str[3] = 'h';
str = str.join('');
There are lot of answers here, and all of them are based on two methods:
METHOD1: split the string using two substrings and stuff the character between them
METHOD2: convert the string to character array, replace one array member and join it
Personally, I would use these two methods in different cases. Let me explain.
#FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.
#vsync, #Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.
But what will happen if I have to make quite a few replacements?
I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:
var str = "... {A LARGE STRING HERE} ...";
for(var i=0; i<100000; i++)
{
var n = '' + Math.floor(Math.random() * 10);
var p = Math.floor(Math.random() * 1000);
// replace character *n* on position *p*
}
I created a fiddle for this, and it's here.
There are two tests, TEST1 (substring) and TEST2 (array conversion).
Results:
TEST1: 195ms
TEST2: 6ms
It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???
What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.
So, it's all about choosing the right tool for the job. Again.
Work with vectors is usually most effective to contact String.
I suggest the following function:
String.prototype.replaceAt=function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
Run this snippet:
String.prototype.replaceAt=function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
var str = "hello world";
str = str.replaceAt(3, "#");
document.write(str);
In Javascript strings are immutable so you have to do something like
var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);
To replace the character in x at i with 'h'
function dothis() {
var x = document.getElementById("x").value;
var index = document.getElementById("index").value;
var text = document.getElementById("text").value;
var length = document.getElementById("length").value;
var arr = x.split("");
arr.splice(index, length, text);
var result = arr.join("");
document.getElementById('output').innerHTML = result;
console.log(result);
}
dothis();
<input id="x" type="text" value="White Dog" placeholder="Enter Text" />
<input id="index" type="number" min="0"value="6" style="width:50px" placeholder="index" />
<input id="length" type="number" min="0"value="1" style="width:50px" placeholder="length" />
<input id="text" type="text" value="F" placeholder="New character" />
<br>
<button id="submit" onclick="dothis()">Run</button>
<p id="output"></p>
This method is good for small length strings but may be slow for larger text.
var x = "White Dog";
var arr = x.split(""); // ["W", "h", "i", "t", "e", " ", "D", "o", "g"]
arr.splice(6, 1, 'F');
/*
Here 6 is starting index and 1 is no. of array elements to remove and
final argument 'F' is the new character to be inserted.
*/
var result = arr.join(""); // "White Fog"
One-liner using String.replace with callback (no emoji support):
// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"
Explained:
//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
if (index == 0) //we want to replace the first character
return 'f'
return character //leaving other characters the same
})
Generalizing Afanasii Kurakin's answer, we have:
function replaceAt(str, index, ch) {
return str.replace(/./g, (c, i) => i == index ? ch : c);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
Let's expand and explain both the regular expression and the replacer function:
function replaceAt(str, index, newChar) {
function replacer(origChar, strIndex) {
if (strIndex === index)
return newChar;
else
return origChar;
}
return str.replace(/./g, replacer);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
The regular expression . matches exactly one character. The g makes it match every character in a for loop. The replacer function is called given both the original character and the index of where that character is in the string. We make a simple if statement to determine if we're going to return either origChar or newChar.
var str = "hello world";
console.log(str);
var arr = [...str];
arr[0] = "H";
str = arr.join("");
console.log(str);
This works similar to Array.splice:
String.prototype.splice = function (i, j, str) {
return this.substr(0, i) + str + this.substr(j, this.length);
};
You could try
var strArr = str.split("");
strArr[0] = 'h';
str = strArr.join("");
this is easily achievable with RegExp!
const str = 'Hello RegEx!';
const index = 11;
const replaceWith = 'p';
//'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);
//< "Hello RegExp"
Using the spread syntax, you may convert the string to an array, assign the character at the given position, and convert back to a string:
const str = "hello world";
function replaceAt(s, i, c) {
const arr = [...s]; // Convert string to array
arr[i] = c; // Set char c at pos i
return arr.join(''); // Back to string
}
// prints "hallo world"
console.log(replaceAt(str, 1, 'a'));
You could try
var strArr = str.split("");
strArr[0] = 'h';
str = strArr.join("");
Check out this function for printing steps
steps(3)
// '# '
// '## '
// '###'
function steps(n, i = 0, arr = Array(n).fill(' ').join('')) {
if (i === n) {
return;
}
str = arr.split('');
str[i] = '#';
str = str.join('');
console.log(str);
steps(n, (i = i + 1), str);
}
#CemKalyoncu: Thanks for the great answer!
I also adapted it slightly to make it more like the Array.splice method (and took #Ates' note into consideration):
spliceString=function(string, index, numToDelete, char) {
return string.substr(0, index) + char + string.substr(index+numToDelete);
}
var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"
If you want to replace characters in string, you should create mutable strings. These are essentially character arrays. You could create a factory:
function MutableString(str) {
var result = str.split("");
result.toString = function() {
return this.join("");
}
return result;
}
Then you can access the characters and the whole array converts to string when used as string:
var x = MutableString("Hello");
x[0] = "B"; // yes, we can alter the character
x.push("!"); // good performance: no new string is created
var y = "Hi, "+x; // converted to string: "Hi, Bello!"
You can extend the string type to include the inset method:
String.prototype.append = function (index,value) {
return this.slice(0,index) + value + this.slice(index);
};
var s = "New string";
alert(s.append(4,"complete "));
Then you can call the function:
You can concatenate using sub-string function at first select text before targeted index and after targeted index then concatenate with your potential char or string. This one is better
const myString = "Hello world";
const index = 3;
const stringBeforeIndex = myString.substring(0, index);
const stringAfterIndex = myString.substring(index + 1);
const replaceChar = "X";
myString = stringBeforeIndex + replaceChar + stringAfterIndex;
console.log("New string - ", myString)
or
const myString = "Hello world";
let index = 3;
myString = myString.substring(0, index) + "X" + myString.substring(index + 1);
I did a function that does something similar to what you ask, it checks if a character in string is in an array of not allowed characters if it is it replaces it with ''
var validate = function(value){
var notAllowed = [";","_",">","<","'","%","$","&","/","|",":","=","*"];
for(var i=0; i<value.length; i++){
if(notAllowed.indexOf(value.charAt(i)) > -1){
value = value.replace(value.charAt(i), "");
value = validate(value);
}
}
return value;
}
Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.
replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings )
Working example: https://codesandbox.io/s/ov7zxp9mjq
function replaceAt(indexArray, [...string]) {
const replaceValue = i => string[i] = <b>{string[i]}</b>;
indexArray.forEach(replaceValue);
return string;
}
And here is another alternate method
function replaceAt(indexArray, [...string]) {
const startTag = '<b>';
const endTag = '</b>';
const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
indexArray.forEach(tagLetter);
return string.join('');
}
And another...
function replaceAt(indexArray, [...string]) {
for (let i = 0; i < indexArray.length; i++) {
string = Object.assign(string, {
[indexArray[i]]: <b>{string[indexArray[i]]}</b>
});
}
return string;
}
Here is my solution using the ternary and map operator. More readable, maintainable end easier to understand if you ask me.
It is more into es6 and best practices.
function replaceAt() {
const replaceAt = document.getElementById('replaceAt').value;
const str = 'ThisIsATestStringToReplaceCharAtSomePosition';
const newStr = Array.from(str).map((character, charIndex) => charIndex === (replaceAt - 1) ? '' : character).join('');
console.log(`New string: ${newStr}`);
}
<input type="number" id="replaceAt" min="1" max="44" oninput="replaceAt()"/>
My safe approach with negative indexes
/**
* #param {string} str
* #param {number} index
* #param {string} replacement
* #returns {string}
*/
static replaceAt (str, index, replacement)
{
if (index < 0) index = str.length + index
if (index < 0 || index >= str.length) throw new Error(`Index (${index}) out of bounds "${str}"`)
return str.substring(0, index) + replacement + str.substring(index + 1)
}
Use it like that:
replaceAt('my string', -1, 'G') // 'my strinG'
replaceAt('my string', 2, 'yy') // 'myyystring'
replaceAt('my string', 22, 'yy') // Uncaught Error: Index (22) out of bounds "my string"
Lets say you want to replace Kth index (0-based index) with 'Z'.
You could use Regex to do this.
var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");
You can use the following function to replace Character or String at a particular position of a String. To replace all the following match cases use String.prototype.replaceAllMatches() function.
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
var retStr = this, repeatedIndex = 0;
for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
if (repeatedIndex == 0 && x == 0) {
repeatedIndex = retStr.indexOf(matchkey);
} else { // matchIndex > 0
repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
}
if (x == matchIndex) {
retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
matchkey = null; // To break the loop.
}
}
return retStr;
};
Test:
var str = "yash yas $dfdas.**";
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
Output:
Index Matched replace : yash yas $dfd*.**
Index Matched replace : yash ~as $dfdas.**
I se this to make a string proper case, that is, the first letter is Upper Case and all the rest are lower case:
function toProperCase(someString){
return someString.charAt(0).toUpperCase().concat(someString.toLowerCase().substring(1,someString.length));
};
This first thing done is to ensure ALL the string is lower case - someString.toLowerCase()
then it converts the very first character to upper case -someString.charAt(0).toUpperCase()
then it takes a substring of the remaining string less the first character -someString.toLowerCase().substring(1,someString.length))
then it concatenates the two and returns the new string -someString.charAt(0).toUpperCase().concat(someString.toLowerCase().substring(1,someString.length))
New parameters could be added for the replacement character index and the replacement character, then two substrings formed and the indexed character replaced then concatenated in much the same way.
The solution does not work for negative index so I add a patch to it.
String.prototype.replaceAt=function(index, character) {
if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
}
"hello world".replace(/(.{3})./, "$1h")
// 'helho world'
The methods on here are complicated.
I would do it this way:
var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");
This is as simple as it gets.

Categories