How to find all occurrences of a character in a string. For example string is: "Hello world"
and user want to now the indexes of string where 'L' is present. Which is in example 2,3 and 9. How to find indexes like this in java-script/jquery ?
You can try something like the following code, from this answer:
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, searchStrLen = searchStr.length;
var 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;
}
For example, if you wanted to find all b's and then write them to the document -
var foo = "foo bar baz bat";
var pos = foo.indexOf("b");
while(pos > -1) {
document.write(pos + "<br />");
pos = foo.indexOf("b", pos+1);
}
Output:
4
8
12
Here is some pseudocode. This is how you should try and work out the logic for problems before you try to start coding.
var indeces = {};
for(each character in string)
if(character == characterImLookingFor)
indeces.add(currentIndex);
return indeces;
function getIndexes(str,char) {
var index = str.indexOf(char);
var indexes = [];
while(index != -1) {
indexes.push(index);
index = str.indexOf(char,index+1);
}
return indexes;
}
Usage:
getIndexes("Hello world","l"); // returns [2,3,9]
You can also use regular expressions to achieve this:
var str = "Give me indexes of i in this string";
var regex = /i/gi, result;
while ((result = regex.exec(str)) ) {
console.log(result.index);
}
//Output: 1, 8, 19, 21, 26, 32
DEMO
Related
I am trying to remove n amount of characters from a given index. Here are the instructions:
"Write a function called removeFromString, which accepts a string, a starting index (number) and a number of characters to remove.
The function should return a new string with the characters removed."
Here is what I have so far:
function removeFromString(str, index, number) {
var sliced = str.slice(index, -number);
return sliced;
}
console.log(
removeFromString('This is a string', 5, 5)
);
It is sort of working, BUT for some reason in addition to removing characters from the given index, it also removes characters from the end of the string. What am I doing wrong?
function removeFromString(str, index, number) {
var outputStringArray = str.split('');
outputStringArray.splice(index, number);
return outputStringArray.join('');
}
console.log(
removeFromString('This is a string', 5, 5)
);
Slice returns the extracted string... so, put two extracted strings together.
function removeFromString(str, index, number) {
var sliced = str.slice(0, index) + str.slice(index + number);
return sliced;
}
console.log(
removeFromString('This is a string', 5, 5)
);
For the Nerds
function removeFromString(str,index,number){
return str.split('').fill('',index,index+number).join('')
}
console.log(removeFromString('This is a string',5,5))
If you convert the String to an Array, you can use the powerful array.splice method. Here's an intentionally verbose example:
let str = "Harry Potter-Evans-Verres and the Methods of Rationality"
removeFromString(str, 12, 13);
function removeFromString(string, startAt, howMany){
const array = Array.from(string)
removedArray = array.splice(12, 13);
let remainingString = array.join("");
let removedString = removedArray.join("");
console.log({remainingString});
console.log({removedString});
return remainingString;
}
This should work:
function removeFromString(str, start, removeCount) {
let newStr = '';
for (let i = 0; i < str.length; i++) {
if (i < start || i >= start + removeCount) {
newStr += str[i];
}
}
return newStr;
}
let test = removeFromString('this is a test', 4, 6);
console.log(test);
So I got a string:
let string = "XABXAX12345BX293993AX9393B33AXAXBXBXBXAAABBX";
and I'd like to extract all occurrences between the strings AX and BXs to get an array like this as result:
let result = ["12345", "9393B33AXAX"];
I've tried to use some kind of regex but I was not really successfull tbh.
let result = string.split(/AX([^AXBX]+)BX/);
Another aproach was a simple for-loop but also this is not working as I've expected. So maybe somebody is able to help me fixing the issues. Please have a look at my code:
let string = "XABXAX12345BX293993AX9393B33AXAXBXBXBXAAABBX"
let result = [];
for (let i=0; i<string.length; i++) {
if (string[i] == "A" && string[i+1] === "X") {
for (let j=i; j<string.length; j++) {
if (string[j] == "B" && string[j+1] === "X") {
let substring = string.substring(i+1, j+1);
result.push(substring)
break;
}
}
}
}
console.log(result);
Here's a simple solution:
function re_esc(str) {
return str.replace(/\W/g, "\\$&");
}
const start = "AX";
const end = "BX";
const re = new RegExp(re_esc(start) + '([\\s\\S]*?)' + re_esc(end), 'g');
const string = "XABXAX12345BX293993AX9393B33AXAXBXBXBXAAABBX";
const results = [];
let m;
while (m = re.exec(string)) {
results.push(m[1]);
}
console.log(results);
We build a regex of the form START(.*?)END, then use it to successively extract matches in a loop.
Here's a relatively straightforward looping approach that doesn't use regexes:
function findOccurrences(str, fromStr, toStr) {
const occurrences = [];
let startIndex = 0;
while (true) {
const fromIndex = str.indexOf(fromStr, startIndex);
if (fromIndex === -1) {
break;
}
const toIndex = str.indexOf(toStr, fromIndex + fromStr.length);
if (toIndex === -1) {
break;
}
const occurrence = str.slice(fromIndex + fromStr.length, toIndex);
occurrences.push(occurrence);
startIndex = toIndex + toStr.length;
}
return occurrences;
}
console.log(
findOccurrences("XABXAX12345BX293993AX9393B33AXAXBXBXBXAAABBX",
"AX", "BX"));
This doesn't include any sanity checks; for instance, you might want to check that fromStr and toStr aren't empty strings.
I am trying to get the index of the exact search string, I have built a function that returns the index the match strings where I need to get the index only with the exact match
here is my function
getIndicesOf = (searchStr, str) => {
var searchStrLen = searchStr.length;
if (searchStrLen === 0) {
return [];
}
var startIndex = 0,
index,
indices = [];
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
console.log("detercting " , indices );
return indices;
};
console.log(getIndicesOf("go" , "go, I am going ")); // [0, 9]
here I go the index of go and going , How can get the index only of the exact match string?
The first occurrence of go also contains a comma. So it is not an exact match.
If you still want to get all the indices of go and go, in the words array, you can use the following script.
var x = "go, I am going go";
arr = x.split(" ");
arr.map((e, i) => (e === "go" || e === "go,") ? i : '').filter(String)
If you need to find the index in the string you can use the below approach
var x = "go, I am going go";
arr = x.split(" "); var index = 0;
arr.map((e, i) => {
var occur = (e === "go" || e === "go,") ? index : '';
index+=e.length+1;
return occur}).filter(String)
replace your while loop with this code,
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
if(str.substring(startIndex,searchStrLen) == searchStr)
{
indices.push(index);
startIndex = index + searchStrLen;
}
}
I would like to search in javascript string and get all string occurrence by word index for example:
var str = 'Hello this is my this is world'
myFindWordIndex(str, 'this is') ==> [1, 4]
(two occurrences of the search string, one starts at word index 1 and one starts at index 4)
the solution can use JQuery
I would split the phrase you're trying to find and where you're trying to find it into words. Then simply check if the phrase contains each piece of the search phrase.
function check(hay, needle, from) {
var i = 1;
while (i < needle.length) {
if (hay[from] != needle[i])
return false;
i++;
from++;
}
return true;
}
function myFindWordIndex(str, findme) {
var indices = [];
var needle = findme.split(" ");
var hay = str.split(" ");
for (var i = 0; i < hay.length - needle.length; i++) {
if (hay[i] == needle[0] && (needle.length==1||check(hay, needle, i)))
indices.push(i);
}
return indices;
}
var str = 'Hello this is my this is world';
console.log(myFindWordIndex(str, 'this is')); // ==> [1, 4]
Here's a clunky solution using Lodash.js.
function run(str, searchingFor) {
return _.flatten(
_.zip(str.split(/\s+/), str.split(/\s+/))
)
.slice(1, -1)
.join(' ')
.match(/\w+\s+\w+/g)
.reduce((a, b, i) => {
return b === searchingFor
? a.concat(i)
: a;
}, []);
}
Here is it running...
run('Hello this is my this is world', 'this is');
// => [1, 4]
Not ideal. Not very portable. But it works.
using function from How to find indices of all occurrences of one string in another in JavaScript? for multi search
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, searchStrLen = searchStr.length;
var 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;
}
function myFindWordIndex(str, search_str) {
var res = [];
$.each(getIndicesOf(search_str, str, true), function(i, v) {
res.push(str.slice(0, v).split(' ').length)
});
return res;
}
adding #Mohammad's answer since it looks the cleanest:
var str = 'Hello this is my this is world'
var pos = myFindWordIndex(str, 'this is');
console.log(pos);
function myFindWordIndex(str, word){
var arr = [];
var wordLength = word.split(" ").length;
var position = 0;
str.split(word).slice(0, -1).forEach(function(value, i){
position += value.trim().split(" ").length;
position += i > 0 ? wordLength : 0;
arr.push(position);
});
return arr;
}
I want something like this:
"abcdab".search(/a/g) //return [0,4]
Is it possible?
You can use the RegExp#exec method several times:
var regex = /a/g;
var str = "abcdab";
var result = [];
var match;
while (match = regex.exec(str))
result.push(match.index);
alert(result); // => [0, 4]
Helper function:
function getMatchIndices(regex, str) {
var result = [];
var match;
regex = new RegExp(regex);
while (match = regex.exec(str))
result.push(match.index);
return result;
}
alert(getMatchIndices(/a/g, "abcdab"));
You could use / abuse the replace function:
var result = [];
"abcdab".replace(/(a)/g, function (a, b, index) {
result.push(index);
});
result; // [0, 4]
The arguments to the function are as follows:
function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
If you only want to find simple characters, or character sequences, you can use indexOf [MDN]:
var haystack = "abcdab",
needle = "a"
index = -1,
result = [];
while((index = haystack.indexOf(needle, index + 1)) > -1) {
result.push(index);
}
You can get all match indexes like this:
var str = "abcdab";
var re = /a/g;
var matches;
var indexes = [];
while (matches = re.exec(str)) {
indexes.push(matches.index);
}
// indexes here contains all the matching index values
Working demo here: http://jsfiddle.net/jfriend00/r6JTJ/
A non-regex variety:
var str = "abcdabcdabcd",
char = 'a',
curr = 0,
positions = [];
while (str.length > curr) {
if (str[curr] == char) {
positions.push(curr);
}
curr++;
}
console.log(positions);
http://jsfiddle.net/userdude/HUm8d/
Another non-regex solution:
function indexesOf(str, word) {
const split = str.split(word)
let pointer = 0
let indexes = []
for(let part of split) {
pointer += part.length
indexes.push(pointer)
pointer += word.length
}
indexes.pop()
return indexes
}
console.log(indexesOf('Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate', 'JavaScript'))
Based on #jfriend00 answer but tidied up:
const getAllIndices = (str, strToFind) => {
const regex = RegExp(strToFind, 'g')
const indices = []
let matches
while (matches = regex.exec(str)) indices.push(matches.index)
return indices
}
console.log(getAllIndices('hello there help me', 'hel'))
console.log(getAllIndices('hello there help me', 'help'))
console.log(getAllIndices('hello there help me', 'xxxx'))