How to get biggest number in textarea? - javascript

I have a textarea like this:
<textarea>
this is a test [1] also this [2] is a test
and again [3] this is a test
</textarea>
Now I need to get the biggest number which is in []. In this case I need to get 3. How can I do that?

You could do:
var result = Math.max.apply(Math, textarea.value.match(/\d+/g).map(Number));
Breaking it up:
textarea.value.match(/\d+/g)
Gets you an array of numbers as strings.
.map(Number)
Maps each entry of the array from a string to a number.
Math.max.apply
Calls Math.max with this as Math and as parameters the mapped array.
Edit: I didn't realize what you needed had to be in between brackets. You'll need to use a capture group for that and it's a little bit more complicated now.
var reg = /\[(\d+)\]/g, numberStrings = [ ], match;
while((match = reg.exec(textarea.value)) !== null){
numberStrings.push(match[1]);
}
var result = Math.max.apply(Math, numberStrings.map(Number));
It's a little bit more tricky to get the array of strings with the numbers.
Another alternative, without using a capture group:
var numbersInBrackets = textarea.value.match(/\[\d+\]/g);
var numbers = numbersInBrackets.map(function(x) {
return Number(x.substring(1, x.length - 1));
});
var result = Math.max.apply(Math, numbers);

Same idea as MinusFour's solution. Uses jQuery but could easily be done without.
var content = $('textarea').val();
var contentArr = content.split(' ');
var nums = [];
for (var i = 0; i < contentArr.length; i++) {
var txt = contentArr[i];
if (txt.match(/[\d]/)) {
nums.push(Number(txt.slice(1,-1)));
}
}
// Max number is Math.max.apply(null, nums)
Full working JSFiddle.

You need to perform 2 actions:
Get all the [(numbers)] with \[(\d+)] regex
Get the max value from the resulting array (see this post)
Array.max = function( array ){
return Math.max.apply( Math, array );
};
var re = /\[(\d+)]/g;
var str = 'this is a test [1] also this [2] is a test\nand again [3] this is a test';
var numbers = []
while ((m = re.exec(str)) !== null) {
numbers.push(Number(m[1]));
}
document.write(Array.max(numbers));

Use this function to find the biggest [number] in any string :
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
DEMO
The following demo calculates the biggest number in your textarea every time you click the button.
It allows you to play around with the textarea and re-test the function with a different text.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
document.getElementById("myButton").addEventListener("click", function() {
alert(biggestNumber(document.getElementById("myTextArea").value));
});
<div>
<textarea rows="4" cols="50" id="myTextArea">
this is a test [1] also this [2] is a test
and again [3] this is a test
</textarea>
</div>
<div>
<button id="myButton">Try me</button>
</div>
See also this Fiddle!

Related

What is the simplest way to do a RegExp for variations on a pattern?

My code (below) searches a string for the 4 possible variations on a pattern that the string may contain dd[Q]dd[A], d[Q]d[A], dd[Z]dd[A], d[Z]d[A]. My goal is to always find the number between character Q and A (or Z and A) and return the number and index position.
I believe my code could be written in a much more efficient manner, but I'm not sure what it would be (I'm a beginner coder). Any thoughts?
{
var str = 'TY 111-222 4Q8A';
var result;
var index;
/*RegExp the 4 possible variations of the pattern*/
var srchAlpha = /\d\d\*?[Q]\d\d\*?[A]/i;
var srchBeta = /\d\*?[Q]\d\*?[A]/i;
var srchGamma = /\d\d\*?[Z]\d\d\*?[A]/i;
var srchDelta = /\d\*?[Z]\d\*?[A]/i;
/*Index the 4 possible variations of the pattern*/
var indexAlpha = str.search(srchAlpha);
var indexBeta = str.search(srchBeta);
var indexGamma = str.search(srchGamma);
var indexDelta = str.search(srchDelta);
/*Determine which variation of the pattern the string contains*/
if (indexAlpha != -1) {
result = str.slice(indexAlpha+3, indexAlpha+5);
index = indexAlpha+3;
} else if (indexBeta != -1) {
result = str.slice(indexBeta+2, indexBeta+3);
index = indexBeta+2;
} else if (indexGamma != -1) {
result = str.slice(indexGamma+3, indexGamma+5);
index = indexGamma+3;
} else if (indexDelta != -1) {
result = str.slice(indexDelta+2, indexDelta+3);
index = indexDelta+2;
} else {
result = "";
index = "";
}
document.getElementById("result").innerHTML = result;
document.getElementById("index").innerHTML = index;
}
<p>result: <span id="result"></span></p>
<p>index: <span id="index"></span></p>
If there might be no digits between the letters, then, I believe, [QZ](\d*)A will do.
Make it [QZ](\d+)A if at least one digit is expected.
If there will be one or two digits, use [QZ](\d{1,2})A.
Do the following to extract the digit(s) and index(es):
const regex = /[QZ](\d+)A/;
const input = "TY 111-222 4Q8A";
const match = input.match(regex);
if (!match)
// no match
const digits = match[1];
const digitsIndexes = input.indexOf(digits);
For two groups of digits (before and after the Q or Z character) use two capturing groups:
const regex = /(\d+)[QZ](\d+)A/;
// ...
const digitGroups = [ match[1], match[2] ];
const digitGroupsIndexes = digitGroups.map(group => input.indexOf(group));
For reference, based on Dmitry Parzhitsky's answer, I have the full answer here.
{
var regex = /(\d+)[QZ](\d+)A/;
var input = "TY 111-222 4Q8A";
var match = input.match(regex);
if (!match) {
digits = "";
digitsIndexes = "";
} else {
var digits = match[2];
var digitsIndexes = input.indexOf(digits);
}
document.getElementById("result").innerHTML = digits;
document.getElementById("index").innerHTML = digitsIndexes;
}
<p>result: <span id="result"></span></p>
<p>index: <span id="index"></span></p>

Regex match after delimiter and find higher number of the match?

I have a match equation
function start() {
var str = "10x2+10x+10y100-20y30";
var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"
var text;
if(match < 10)
{text = "less 10";}
else if(match == "10")
{text == "equal";}
else
{text ="above 10";}
document.getElementById('demo').innerHTML=text;
}
start();
<p id="demo"></p>
i need match the power values and also getting out with higher power value only.
example :10x2+10y90+9x91 out --> "90".
what wrong with my and corret my regex match with suitable format.Thank You
The variable match contains all the powers that matches your regex, not just one. You'll have to iterate over them to find the greatest.
I took your code and modified it a bit to work :
function start() {
var str = "10x2+10x+10y100-20y30";
var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"
var max = 0;
for (var i = 0; i < match.length; i++) { // Iterate over all matches
var currentValue = parseInt(match[i].substring(1)); // Get the value of that match, without using the first letter
if (currentValue > max) {
max = currentValue; // Update maximum if it is greater than the old one
}
}
document.getElementById('demo').innerHTML=max;
}
start();
<p id="demo"></p>
Try this:
const str = '10x2+10x+10y100-20y30'
,regex = /([a-z])=?(\d+)/g
const matches = []
let match
while ((match = regex.exec(str)) !== null) {
matches.push(match[2])
}
const result = matches.reduce((a, b) => Number(a) > Number(b) ? a : b)
console.log(result)

Test a Textarea for All Keywords in an Array

I found a variation on this code elsewhere in StackOverflow. It takes all words from a textarea and converts them into a regular expression. It then tests an array to see if all the words in the regex are contained in the array:
<textarea id="inputtext" type="text"></textarea>
<input id="searchbutton" type="button" value="Click me" />
var links = new Array("taxi","Alpha","runway");
$("#searchbutton").click(function () {
var query = $("#inputtext").val();
var querywords = query.split(',');
for (var i = 0; i < querywords.length; i++) {
var regex = new RegExp('(?=.*\\b' + querywords[i].split(' ').join('\\b)(?=.*\\b') + '\\b)', 'i', 'g');
for (var j = 0; j < links.length; j++) {
if (regex.test(links[j])) {
console.log("Correct");
}
}
}
});
How can I reverse the process so the program returns "true" if the textarea words includes all of the keywords within the array? For example, if the textarea had the sentence "Taxi to the runway via taxiway alpha," and the array named "links" contained the keywords "taxi" "alpha" and "runway", the program would return "true".
That script you have seems to check if any of the words appears somewhere in the array. What you want is the every Array method:
var text = "Taxi to the runway via taxiway alpha",
links = ["taxi", "alpha", "runway"];
console.log( links.every(function(word) {
return new RegExp("\\b"+word+"\\b", "i").test(text);
}) ); // true
The methods provided by other answers are simple, but they could be more efficient.
It's almost always better to use an object as a map to speed up lookups instead of having to search the entiry array everytime.
var words = ['word1', 'word2'],
wordsMap = 'text area content, word1 and word2'.split(/\W+/).reduce(function (obj, word) {
obj[word] = true;
return obj;
}, {}),
areWordsAllContained = words.every(function (word) {
return wordsMap[word.toLowerCase()];
});
console.log(areWordsAllContained); //true
EDIT: I've changed the splitting regex from \s+ to \W+ to make sure that it splits on every non-word characters.
A non-regex way would be:
var arr = ['word1', 'word2'], haystack = textArea.value.toLowerCase().split(/\s+/);
var result = true, i = 0;
for(i=0; i<arr.length; i++) {
if(haystack.indexOf(arr[i].toLowerCase()) === -1) {
result = false;
break;
}
}

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

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