Replace consecutive white spaces between words with one hyphen - javascript

The question is from freecodecamp Link
Fill in the urlSlug function so it converts a string title and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use replace. Here are the requirements:
The input is a string with spaces and title-cased words
The output is a string with the spaces between words replaced by a
hyphen (-)
The output should be all lower-cased letters
The output should not have any spaces
// the global variable
var globalTitle = " Winter Is Coming";
function urlSlug(title) {
let toArr = title.split("");
let newArr = toArr.map(a=> {
if(a==" "){
a= "-";
}
return a.toLowerCase();
} );
if(newArr[0] == "-"){
newArr.splice(0,1);
}
let finalArr = newArr.join("");
return finalArr;
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
console.log(urlSlug(globalTitle));
Right now I have not been able to solve how I could get rid of the extra hyphen from the output.
I'm not supposed to use replace.

You could do this easily using trim() and a simple regex:
var globalTitle = " Winter Is Coming Now ";
var slug = globalTitle.trim().replace(/[ ]+/g, '-').toLowerCase();
console.log(slug);
[ ]+ ensures that any number of spaces (1 or more) gets replaced with a minus sign once.
If for some reason you can't use replace, you could use Array.filter() like so:
var title = " Winter Is Coming Now ";
var slug = title.split(" ").filter(word => word.length > 0).join("-").toLowerCase();
console.log(slug);

I was working on it till now , Haven't looked at the answers.
But I solved it this way. Might be inefficient.
// the global variable
var globalTitle = "Winter Is Coming";
function urlSlug(title) {
let toArr = title.split("");
let newArr = toArr.map(a=> {
if(a==" "){
a= "-";
}
return a.toLowerCase();
} );
if(newArr[0] == "-"){
newArr.splice(0,1);
}
for(let i=0;i<newArr.length;i++){
if(newArr[i-1]=="-"&& newArr[i]=="-")
{
newArr.splice(i,1,"");
}
}
let finalArr = newArr.join("");
return finalArr;
}
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
console.log(urlSlug(globalTitle));

Another option would be to continue your thought of split() and then use reduce to reduce the elements of the array to a single output:
var globalTitle = " Winter Is Coming";
function urlSlug(title) {
let split = title.split(' ');
return split.reduce((accumulator, currentValue, index) => {
if (currentValue.length > 0) {
accumulator += currentValue.toLowerCase();
accumulator += (index < split.length - 1) ? '-' : '';
}
return accumulator;
});
}
console.log(urlSlug(globalTitle));

Related

Writing function that returns string but with all five or more letters reversed JS

first time posting. I'm writing a function in js that reverses words with more than 5 characters in a given string. It works, but I think it is adding extra "space" strings that it doesn't need if the string inputted is only one word. I know I have too many variables and there is a way better way to do this. I'm pretty new to this, but anything helps. Thanks!
const exString = "Hey fellow warriors"
function spinWords(string){
let newWord = string.split(' ');
let fiveWord = "";
let lessWord = "";
for(i=0; i<newWord.length;i++){
if(newWord[i].length >=5){
fiveWord += newWord[i].split('').reverse() + ' ';
}
else{
lessWord += newWord[i]
}
}
newFiveWord = fiveWord.replace(/,/g,'');
return lessWord + ' ' + newFiveWord
}
console.log(spinWords(exString));
const spinWords = str => str
.split(' ')
.map(word => word.length >= 5
? [...word].reverse().join('')
: word)
.join(' ')
console.log(spinWords("Hey fellow warriors"))
Turn the string into an array of words
Modify each word. If 5+ letters: [..word] turns the string into an array of letters ('hi' > ['h', 'i']). Then reverse the array, and turn the letters back into one string.
Undo step one by turning the array into one string.
function reversedText() {
let text = prompt("Enter text");
const words = text?.split(" ");
const newText = words.map((word) => {
if (word.length >= 5) {
return (word.split("").reverse().join(""));
}
return word;
});
if (newText.length > 0) {
return newText.filter(notNull).join(" ");
} else {
return 'Your sentence have words which have length less than 5';
}
}
function notNull(value) {
return value != null
}
console.log(reversedText());

How to reverse initial string and save space order

How to reverse initial string and save space order more correctly than in my solution. I need to transfrom initial string, to do it reversed but keep the same order of spaces as initiall string
'some text with spaces' //=> "seca psht iwtx etemos"
function test(str, result = "") {
let res = str.split('').reverse().join('')
for (let i = 0; i < res.length; i++) {
if (str[i] === " ") {
result += ` ${res[i]}`
str[i + 1];
} else if (str[i] !== " " && res[i] === " ") {
result += ""
} else {
result += res[i];
}
}
return result
}
console.log(test('some text with spaces')) //=> "seca psht iwtx etemos"
function test(str) {
const letters = str.split(""); // make array so we can modify it
const spaceIndexes = letters.reduce((arr, letter, index) => {
if (letter === " ") arr.push(index);
return arr;
}, []);
const reversed = letters.filter(l => l !== ' ').reverse(); // reverse and delete spaces
spaceIndexes.forEach((index) => reversed.splice(index, 0, " ")); // insert spaces at previous places
return reversed.join(""); // return as a string
}
You could take a single loop without splitting and get the non space characters from the end and insert spaces if one is found at the actual length of the new string.
function test(str) {
let i = str.length,
s = '';
while (i--) {
if (str[i] === ' ') continue;
while (str[s.length] === ' ') s += ' ';
s += str[i];
}
return s;
}
console.log(test('some text with spaces'));
This will return all non-blank letters in a reverse order with all blanks at the positions of the original string:
function test(str) {
let i=-1,spaces=[];
while ((i=str.indexOf(' ',i+1))>-1) spaces.push(i); // find space positions
let res=str.replace(/ /g,'').split('').reverse(); // remove spaces and
// turn into array and reverse it
spaces.forEach(i=>res.splice(i,0,' ')) // put spaces back into array
return res.join(''); // turn array to string and return
}
let str="let us try this function.";
console.log(str);
console.log(test(str))
Not exactly sure if there is better solution than this. But the best I could think of for now
The algorithm is
Find out the space indexes in the given string
Reverse the same sting
Add the space as per indexes got above and replace any additional spaces in string
function test(str) {
const mapping = {};
const pattern = /\s+/g;
while (match = pattern.exec(str)) {
mapping[match.index] = true;
}
return str.split('').reverse().reduce((acc, cur, index) => {
if(mapping[index]) acc += ' ';
acc += cur.replace(pattern, '');
return acc;
}, '');
}
// seca psht iwtx etemos
console.log(test('some text with spaces'))
let theString = "some text with spaces";
let spaceArr = [] // we will store spaces position in this array
let pos = 0
let strArr = theString.split(" ")
for(let i=0; i<strArr.length-1; i++){
spaceArr.push(pos + strArr[i].length)
pos = pos+1 + strArr[i].length
}
// now lets remove spaces , reverse string, put back orignal spaces
let res = strArr.join("").split("").reverse().join("").split("")
spaceArr.forEach((item,index)=>{
res.splice(item,0," ")
})
console.log(res.join(""))

How to get odd and even position characters from a string?

I'm trying to figure out how to remove every second character (starting from the first one) from a string in Javascript.
For example, the string "This is a test!" should become "hsi etTi sats!"
I also want to save every deleted character into another array.
I have tried using replace method and splice method, but wasn't able to get them to work properly. Mostly because replace only replaces the first character.
function encrypt(text, n) {
if (text === "NULL") return n;
if (n <= 0) return text;
var encArr = [];
var newString = text.split("");
var j = 0;
for (var i = 0; i < text.length; i += 2) {
encArr[j++] = text[i];
newString.splice(i, 1); // this line doesn't work properly
}
}
You could reduce the characters of the string and group them to separate arrays using the % operator. Use destructuring to get the 2D array returned to separate variables
let str = "This is a test!";
const [even, odd] = [...str].reduce((r,char,i) => (r[i%2].push(char), r), [[],[]])
console.log(odd.join(''))
console.log(even.join(''))
Using a for loop:
let str = "This is a test!",
odd = [],
even = [];
for (var i = 0; i < str.length; i++) {
i % 2 === 0
? even.push(str[i])
: odd.push(str[i])
}
console.log(odd.join(''))
console.log(even.join(''))
It would probably be easier to use a regular expression and .replace: capture two characters in separate capturing groups, add the first character to a string, and replace with the second character. Then, you'll have first half of the output you need in one string, and the second in another: just concatenate them together and return:
function encrypt(text) {
let removedText = '';
const replacedText1 = text.replace(/(.)(.)?/g, (_, firstChar, secondChar) => {
// in case the match was at the end of the string,
// and the string has an odd number of characters:
if (!secondChar) secondChar = '';
// remove the firstChar from the string, while adding it to removedText:
removedText += firstChar;
return secondChar;
});
return replacedText1 + removedText;
}
console.log(encrypt('This is a test!'));
Pretty simple with .reduce() to create the two arrays you seem to want.
function encrypt(text) {
return text.split("")
.reduce(({odd, even}, c, i) =>
i % 2 ? {odd: [...odd, c], even} : {odd, even: [...even, c]}
, {odd: [], even: []})
}
console.log(encrypt("This is a test!"));
They can be converted to strings by using .join("") if you desire.
I think you were on the right track. What you missed is replace is using either a string or RegExp.
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.
Source: String.prototype.replace()
If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier
Source: JavaScript String replace() Method
So my suggestion would be to continue still with replace and pass the right RegExp to the function, I guess you can figure out from this example - this removes every second occurrence for char 't':
let count = 0;
let testString = 'test test test test';
console.log('original', testString);
// global modifier in RegExp
let result = testString.replace(/t/g, function (match) {
count++;
return (count % 2 === 0) ? '' : match;
});
console.log('removed', result);
like this?
var text = "This is a test!"
var result = ""
var rest = ""
for(var i = 0; i < text.length; i++){
if( (i%2) != 0 ){
result += text[i]
} else{
rest += text[i]
}
}
console.log(result+rest)
Maybe with split, filter and join:
const remaining = myString.split('').filter((char, i) => i % 2 !== 0).join('');
const deleted = myString.split('').filter((char, i) => i % 2 === 0).join('');
You could take an array and splice and push each second item to the end of the array.
function encrypt(string) {
var array = [...string],
i = 0,
l = array.length >> 1;
while (i <= l) array.push(array.splice(i++, 1)[0]);
return array.join('');
}
console.log(encrypt("This is a test!"));
function encrypt(text) {
text = text.split("");
var removed = []
var encrypted = text.filter((letter, index) => {
if(index % 2 == 0){
removed.push(letter)
return false;
}
return true
}).join("")
return {
full: encrypted + removed.join(""),
encrypted: encrypted,
removed: removed
}
}
console.log(encrypt("This is a test!"))
Splice does not work, because if you remove an element from an array in for loop indexes most probably will be wrong when removing another element.
I don't know how much you care about performance, but using regex is not very efficient.
Simple test for quite a long string shows that using filter function is on average about 3 times faster, which can make quite a difference when performed on very long strings or on many, many shorts ones.
function test(func, n){
var text = "";
for(var i = 0; i < n; ++i){
text += "a";
}
var start = new Date().getTime();
func(text);
var end = new Date().getTime();
var time = (end-start) / 1000.0;
console.log(func.name, " took ", time, " seconds")
return time;
}
function encryptREGEX(text) {
let removedText = '';
const replacedText1 = text.replace(/(.)(.)?/g, (_, firstChar, secondChar) => {
// in case the match was at the end of the string,
// and the string has an odd number of characters:
if (!secondChar) secondChar = '';
// remove the firstChar from the string, while adding it to removedText:
removedText += firstChar;
return secondChar;
});
return replacedText1 + removedText;
}
function encrypt(text) {
text = text.split("");
var removed = "";
var encrypted = text.filter((letter, index) => {
if(index % 2 == 0){
removed += letter;
return false;
}
return true
}).join("")
return encrypted + removed
}
var timeREGEX = test(encryptREGEX, 10000000);
var timeFilter = test(encrypt, 10000000);
console.log("Using filter is faster ", timeREGEX/timeFilter, " times")
Using actually an array for storing removed letters and then joining them is much more efficient, than using a string and concatenating letters to it.
I changed an array to string in filter solution to make it the same like in regex solution, so they are more comparable.

Based on user's choice for CharAt, how can I add the rest of the sentence?

I have this simple function, where user can type a sentence and it will capitalze one letter, based on user's choice. For example if user choose to capitalize first letter for sentence "hey" he would write titleCase("hey", 0) but it will only return that one capitalized letter instead of the whole "Hey" word. It's because I have splited it into array, but how can I return the whole word, not only the capitalized one? My code
function titleCase(str, userChoice) {
var string = str;
var split = string.split(" ");
for (i = 0; i < split.length; i++) {
split[i] = split[i].charAt(userChoice).toUpperCase(); + split[i].slice(0);
}
console.log (split.join(" "));
}
titleCase();
How about this?
Just capitalize the index user selected and then return the string.
function titleCase(str, userChoice) {
var string = str;
var split = string.split("");
split[userChoice] = split[userChoice].toUpperCase();
return (split.join(''));
}
console.log(titleCase('hey', 0))
Issue I noticed in your code:
string.split(" "); -> this will split the string at space but your string is one word so it is never split.
function titleCase(str, userChoice) {
var str = str;
var split = str.split(" ");
split[userChoice] = capitalize(split[userChoice]);
return split.join(" ");
}
function capitalize(s) {
return s[0].toUpperCase() + s.substr(1, s.length - 1)
}
console.log(titleCase('hello world', 0));
console.log(titleCase('hello world', 1));

Replacing dashes "-" with correctly guessed letter in Hangman game for javascript [duplicate]

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

Resources