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'))
Related
I have the following string
server:all, nit:4545, search:dql has map
with the regular expression /(\w+):((?:"[^"]*"|[^:,])*)/g I get
["server:all", "nit:4545", "search:dql has map"] //Array
But I want to get
{server:"all","nit":"4545","search":"dql has map"}
OR
[{server:"all"},{"nit":"4545"},{"search":"dql has map"}]
You can use a simple regex for key:value and use a look using exec:
var str = 'server:all, nit:4545, search:dql has map';
var re = /([\w-]+):([^,]+)/g;
var m;
var map = {};
while ((m = re.exec(str)) != null) {
map[m[1]] = m[2];
}
console.log(map);
You can use String#replace to loop over the matches and captures and assign those to an empty object.
const string = 'server:all, nit:4545, search:dql has map';
const regex = /(\w+):((?:"[^"]*"|[^:,])*)/g;
const map = {};
string.replace(regex, (m, c1, c2) => {
map[c1] = c2;
});
console.log(map);
For your example data, you could also first split on a comma and then split on a colon:
let str = "server:all, nit:4545, search:dql has map";
let result = {};
str.split(',').forEach(function(elm) {
[k, v] = elm.trim().split(':');
result[k] = v;
});
console.log(result);
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 need to count the characters from a to z in an array.
For example I have an array like this:
["max","mona"]
The desired result would be something like this:
a=2, m=2, n=1, o=1, x=1
It would be great, if anyone could help me :)
You can use two forEach loops and return object
var ar = ["max", "mona"], o = {}
ar.forEach(function(w) {
w.split('').forEach(function(e) {
return o[e] = (o[e] || 0) + 1;
});
});
console.log(o)
Or with ES6 you can use arrow function
var ar = ["max","mona"], o = {}
ar.forEach(w => w.split('').forEach(e => o[e] = (o[e] || 0)+1));
console.log(o)
As #Alex.S suggested you can first use join() to return string, then split() to return array and then you can also use reduce() and return object.
var ar = ["max", "mona"];
var result = ar.join('').split('').reduce(function(o, e) {
return o[e] = (o[e] || 0) + 1, o
}, {});
console.log(result)
You can use just one forEach loop and return object
var ar = [ "bonjour", "coucou"], map = {};
ar.join("").split("").forEach(e => map[e] = (map[e] || 0)+1);
console.log(map);
Live Demo
https://repl.it/C17p
I would do it like this;
var a = ["max","mona"],
charCount = a.reduce((p,w) => w.split("").reduce((t,c) => (t[c] ? t[c]++: t[c] = 1,t),p),{});
console.log(charCount);
public static void main (String[] args) throws java.lang.Exception
{
String[] original = {"The","Quick","Brown","Fox","Jumps","Over","The","Lazy","Dog"};
String singleString ="";
for(String str : original )
{
singleString += str;
}
System.out.println(singleString);
char[] chars = singleString.toLowerCase().toCharArray();
Arrays.sort(chars);
String result="";
for(int i=0;i<chars.length;)
{
result += chars[i]+"=";
int count=0;
do {
count++;
i++;
} while (i<chars.length-1 && chars[i-1]==chars[i]);
result += Integer.toString(count)+",";
}
System.out.println(result.substring(0,result.length()-1));
}
The solution using Array.join, Array.sort and String.split functions:
var arr = ["max","mona"],
counts = {};
arr = arr.join("").split(""); // transforms the initial array into array of single characters
arr.sort();
arr.forEach((v) => (counts[v] = (counts[v])? ++counts[v] : 1));
console.log(counts); // {a: 2, m: 2, n: 1, o: 1, x: 1}
Try this:
var words = ['max', 'mona'],
output = {};
words.forEach(function(word){
for(i=0; i < word.split('').length; i++){
if(output[word[i]])
output[word[i]] += 1;
else{
output[word[i]] = 1;
}
}
});
ps: sorry for the code not being formatted, I'm still getting used to the editor =)
I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method
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