Javascript: find all occurrences of word in text document - javascript

I'm trying to write a Javascript function to find indices of all occurrences of a word in a text document. Currently this is what I have--
//function that finds all occurrences of string 'needle' in string 'haystack'
function getMatches(haystack, needle) {
if(needle && haystack){
var matches=[], ind=0, l=needle.length;
var t = haystack.toLowerCase();
var n = needle.toLowerCase();
while (true) {
ind = t.indexOf(n, ind);
if (ind == -1) break;
matches.push(ind);
ind += l;
}
return matches;
}
However, this gives me a problem since this matches the occurrences of the word even when it's part of a string. For example, if the needle is "book" and haystack is "Tom wrote a book. The book's name is Facebook for dummies", the result is the index of 'book', 'book's' and 'Facebook', when I want only the index of 'book'. How can I accomplish this? Any help is appreciated.

Here's the regex I propose:
/\bbook\b((?!\W(?=\w))|(?=\s))/gi
To fix your problem. Try it with the exec() method. The regexp I provided will also consider words like "booklet" that occur in the example sentence you provided:
function getMatches(needle, haystack) {
var myRe = new RegExp("\\b" + needle + "\\b((?!\\W(?=\\w))|(?=\\s))", "gi"),
myArray, myResult = [];
while ((myArray = myRe.exec(haystack)) !== null) {
myResult.push(myArray.index);
}
return myResult;
}
Edit
I've edited the regexp to account for words like "booklet" as well. I've also reformatted my answer to be similar to your function.
You can do some testing here

Try this:
function getMatches(searchStr, str) {
var ind = 0, searchStrL = searchStr.length;
var index, matches = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, ind)) > -1) {
matches.push(index);
ind = index + searchStrL;
}
return matches;
}
indexOf returns the position of the first occurrence of book.
var str = "Tom wrote a book. The book's name is Facebook for dummies";
var n = str.indexOf("book");

I don't know what is going on there but I can offer a better solution using a regex.
function getMatches(haystack, needle) {
var regex = new RegExp(needle.toLowerCase(), 'g'),
result = [];
haystack = haystack.toLowerCase();
while ((match = regex.exec(haystack)) != null) {
result.push(match.index);
}
return result;
}
Usage:
getMatches('hello hi hello hi hi hi hello hi hello john hi hi', 'hi');
Result => [6, 15, 18, 21, 30, 44, 47]
Conserning your book vs books problem, you just need to provide "book " with a space.
Or in the function you could do.
needle = ' ' + needle + ' ';

The easiest way might be using text.match(RegX) function. For example you can write something like this for a case insensitive search:
"This is a test. This is a Test.".match(/test/gi)
Result:
(2) ['test', 'Test']
Or this one for case sensitive scenarios:
"This is a test. This is a Test.".match(/test/g)
Result:
['test']
let myControlValue=document.getElementById('myControl').innerText;
document.getElementById('searchResult').innerText=myControlValue.match(/test/gi)
<p id='myControl'>This is a test. Just a Test
</p>
<span><b>Search Result:</b></span>
<div id='searchResult'></div>

Related

Why does my text disappear in 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.

Javascript replace not working in array string element [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.

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.

Change a single character of a string [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.

How to find indices of all occurrences of one string in another in JavaScript?

I'm trying to find the positions of all occurrences of a string in another string, case-insensitive.
For example, given the string:
I learned to play the Ukulele in Lebanon.
and the search string le, I want to obtain the array:
[2, 25, 27, 33]
Both strings will be variables - i.e., I can't hard-code their values.
I figured that this was an easy task for regular expressions, but after struggling for a while to find one that would work, I've had no luck.
I found this example of how to accomplish this using .indexOf(), but surely there has to be a more concise way to do it?
var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
UPDATE
I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.
function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
One liner using String.prototype.matchAll (ES2020):
[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)
Using your values:
const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]
If you're worried about doing a spread and a map() in one line, I ran it with a for...of loop for a million iterations (using your strings). The one liner averages 1420ms while the for...of averages 1150ms on my machine. That's not an insignificant difference, but the one liner will work fine if you're only doing a handful of matches.
See matchAll on caniuse
Here is regex free version:
function indexes(source, find) {
if (!source) {
return [];
}
// if find is empty string return all indexes.
if (!find) {
// or shorter arrow function:
// return source.split('').map((_,i) => i);
return source.split('').map(function(_, i) { return i; });
}
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
indexes("I learned to play the Ukulele in Lebanon.", "le")
EDIT: and if you want to match strings like 'aaaa' and 'aa' to find [0, 2] use this version:
function indexes(source, find) {
if (!source) {
return [];
}
if (!find) {
return source.split('').map(function(_, i) { return i; });
}
var result = [];
var i = 0;
while(i < source.length) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
i += find.length;
} else {
i++;
}
}
return result;
}
You sure can do this!
//make a regular expression out of your needle
var needle = 'le'
var re = new RegExp(needle,'gi');
var haystack = 'I learned to play the Ukulele';
var results = new Array();//this is the results you want
while (re.exec(haystack)){
results.push(re.lastIndex);
}
Edit: learn to spell RegExp
Also, I realized this isn't exactly what you want, as lastIndex tells us the end of the needle not the beginning, but it's close - you could push re.lastIndex-needle.length into the results array...
Edit: adding link
#Tim Down's answer uses the results object from RegExp.exec(), and all my Javascript resources gloss over its use (apart from giving you the matched string). So when he uses result.index, that's some sort of unnamed Match Object. In the MDC description of exec, they actually describe this object in decent detail.
I am a bit late to the party (by almost 10 years, 2 months), but one way for future coders is to do it using while loop and indexOf()
let haystack = "I learned to play the Ukulele in Lebanon.";
let needle = "le";
let pos = 0; // Position Ref
let result = []; // Final output of all index's.
let hayStackLower = haystack.toLowerCase();
// Loop to check all occurrences
while (hayStackLower.indexOf(needle, pos) != -1) {
result.push(hayStackLower.indexOf(needle , pos));
pos = hayStackLower.indexOf(needle , pos) + 1;
}
console.log("Final ", result); // Returns all indexes or empty array if not found
If you just want to find the position of all matches I'd like to point you to a little hack:
var haystack = 'I learned to play the Ukulele in Lebanon.',
needle = 'le',
splitOnFound = haystack.split(needle).map(function (culm)
{
return this.pos += culm.length + needle.length
}, {pos: -needle.length}).slice(0, -1); // {pos: ...} – Object wich is used as this
console.log(splitOnFound);
It might not be applikable if you have a RegExp with variable length but for some it might be helpful.
This is case sensitive. For case insensitivity use String.toLowerCase function before.
const findAllOccurrences = (str, substr) => {
str = str.toLowerCase();
let result = [];
let idx = str.indexOf(substr)
while (idx !== -1) {
result.push(idx);
idx = str.indexOf(substr, idx+1);
}
return result;
}
console.log(findAllOccurrences('I learned to play the Ukulele in Lebanon', 'le'));
I would recommend Tim's answer. However, this comment by #blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + 1;
}
return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.
P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.
Here is a simple code snippet:
function getIndexOfSubStr(str, searchToken, preIndex, output) {
var result = str.match(searchToken);
if (result) {
output.push(result.index +preIndex);
str=str.substring(result.index+searchToken.length);
getIndexOfSubStr(str, searchToken, preIndex, output)
}
return output;
}
var str = "my name is 'xyz' and my school name is 'xyz' and my area name is 'xyz' ";
var searchToken ="my";
var preIndex = 0;
console.log(getIndexOfSubStr(str, searchToken, preIndex, []));
Thanks for all the replies. I went through all of them and came up with a function that gives the first an last index of each occurrence of the 'needle' substring . I am posting it here in case it will help someone.
Please note, it is not the same as the original request for only the beginning of each occurrence. It suits my usecase better because you don't need to keep the needle length.
function findRegexIndices(text, needle, caseSensitive){
var needleLen = needle.length,
reg = new RegExp(needle, caseSensitive ? 'gi' : 'g'),
indices = [],
result;
while ( (result = reg.exec(text)) ) {
indices.push([result.index, result.index + needleLen]);
}
return indices
}
Check this solution which will able to find same character string too, let me know if something missing or not right.
function indexes(source, find) {
if (!source) {
return [];
}
if (!find) {
return source.split('').map(function(_, i) { return i; });
}
source = source.toLowerCase();
find = find.toLowerCase();
var result = [];
var i = 0;
while(i < source.length) {
if (source.substring(i, i + find.length) == find)
result.push(i++);
else
i++
}
return result;
}
console.log(indexes('aaaaaaaa', 'aaaaaa'))
console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))
console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))
console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
Follow the answer of #jcubic, his solution caused a small confusion for my case
For example var result = indexes('aaaa', 'aa') will return [0, 1, 2] instead of [0, 2]
So I updated a bit his solution as below to match my case
function indexes(text, subText, caseSensitive) {
var _source = text;
var _find = subText;
if (caseSensitive != true) {
_source = _source.toLowerCase();
_find = _find.toLowerCase();
}
var result = [];
for (var i = 0; i < _source.length;) {
if (_source.substring(i, i + _find.length) == _find) {
result.push(i);
i += _find.length; // found a subText, skip to next position
} else {
i += 1;
}
}
return result;
}
Here's my code (using search and slice methods)
let s = "I learned to play the Ukulele in Lebanon"
let sub = 0
let matchingIndex = []
let index = s.search(/le/i)
while( index >= 0 ){
matchingIndex.push(index+sub);
sub = sub + ( s.length - s.slice( index+1 ).length )
s = s.slice( index+1 )
index = s.search(/le/i)
}
console.log(matchingIndex)
This is what I usually use to get a string index also according to its position.
I pass following parameters:
search: the string where to search for
find: the string to find
position ('all' by default): the position by which the find string appears in search string
(if 'all' it returns the complete array of indexes)
(if 'last' it returns the last position)
function stringIndex (search, find, position = "all") {
var currIndex = 0, indexes = [], found = true;
while (found) {
var searchIndex = search.indexOf(find);
if (searchIndex > -1) {
currIndex += searchIndex + find.length;
search = search.substr (searchIndex + find.length);
indexes.push (currIndex - find.length);
} else found = false; //no other string to search for - exit from while loop
}
if (position == 'all') return indexes;
if (position > indexes.length -1) return [];
position = (position == "last") ? indexes.length -1 : position;
return indexes[position];
}
//Example:
var myString = "Joe meets Joe and together they go to Joe's house";
console.log ( stringIndex(myString, "Joe") ); //0, 10, 38
console.log ( stringIndex(myString, "Joe", 1) ); //10
console.log ( stringIndex(myString, "Joe", "last") ); //38
console.log ( stringIndex(myString, "Joe", 5) ); //[]
Hi friends this is just another way of finding indexes of matching phrase using reduce and a helper method. Of course RegExp is more convenient and perhaps is internally implemented somehow like this. I hope you find it useful.
function findIndexesOfPhraseWithReduce(text, phrase) {
//convert text to array so that be able to manipulate.
const arrayOfText = [...text];
/* this function takes the array of characters and
the search phrase and start index which comes from reduce method
and calculates the end with length of the given phrase then slices
and joins characters and compare it whith phrase.
and returns True Or False */
function isMatch(array, phrase, start) {
const end = start + phrase.length;
return (array.slice(start, end).join('')).toLowerCase() ===
phrase.toLowerCase();
}
/* here we reduce the array of characters and test each character
with isMach function which takes "current index" and matches the phrase
with the subsequent character which starts from current index and
ends at the last character of phrase(the length of phrase). */
return arrayOfText.reduce((acc, item, index) => isMatch(arrayOfText, phrase,
index) ? [...acc, index] : acc, []);
}
findIndexesOfPhraseWithReduce("I learned to play the Ukulele in Lebanon.", "le");
function findIndexesOfPhraseWithReduce(text, phrase) {
const arrayOfText = [...text];
function isMatch(array, phrase, start) {
const end = start + phrase.length;
return (array.slice(start, end).join('')).toLowerCase() ===
phrase.toLowerCase();
}
return arrayOfText.reduce((acc, item, index) => isMatch(arrayOfText, phrase,
index) ? [...acc, index] : acc, []);
}
console.log(findIndexesOfPhraseWithReduce("I learned to play the Ukulele in Lebanon.", "le"));
function countInString(searchFor,searchIn){
var results=0;
var a=searchIn.indexOf(searchFor)
while(a!=-1){
searchIn=searchIn.slice(a*1+searchFor.length);
results++;
a=searchIn.indexOf(searchFor);
}
return results;
}
the below code will do the job for you :
function indexes(source, find) {
var result = [];
for(i=0;i<str.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
indexes("hello, how are you", "ar")
Use String.prototype.match.
Here is an example from the MDN docs itself:
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

Categories

Resources