Looping through a String - javascript

I want to get every word that is shown after the word and.
var s = "you have a good day and time works for you and I'll make sure to
get the kids together and that's why I was asking you to do the needful and
confirm"
for (var  i= 0 ; i <= 3; i++){
 var body = s;
 var and = body.split("and ")[1].split(" ")[0];
 body = body.split("and ")[1].split(" ")[1];
 console.log(and);
}
How do I do this?!

Simplest thing is probably to use a regular expression looking for "and" followed by whitespace followed by the "word" after it, for instance something like /\band\s*([^\s]+)/g:
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var rex = /\band\s*([^\s]+)/g;
var match;
while ((match = rex.exec(s)) != null) {
console.log(match[1]);
}
You may well need to tweak that a bit (for instance, \b ["word boundary"] considers - a boundary, which you may not want; and separately, your definition of "word" may be different from [^\s]+, etc.).

at first you need to split the whole string in "and ", after that you have to split every element of given array into spaces, and the first element of the second given array will be the first word after the "and" word.
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"
var body = s;
var and = body.split("and ");
for(var i =0; i<and.length;i++){
console.log(and[i].split(" ")[0]);
}

You can split, check for "and" word, and get next one:
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var a = s.split(' ');
var cont = 0;
var and = false;
while (cont < a.length) {
if (and) {
console.log(a[cont]);
}
and = (a[cont] == 'and');
cont++;
}

Another way to do this using replace
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"
s.replace(/and\s+([^\s]+)/ig, (match, word) => console.log(word))

Related

Javascript regex replace with different values

I'd like to know if it is possible to replace every matching pattern in the string with not one but different values each time.
Let's say I found 5 matches in a text and I want to replace first match with a string, second match with another string, third match with another and so on... is it achievable?
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
"I'm very upset, very distress, very agitated, very annoyed and very pissed".replace(/very/g, function() {
//replace 5 matches of the keyword every with 5 synonyms in the array
});
You may try to replace the matches inside a replace callback function:
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
var cnt = 0;
console.log("I'm very upset, very distress, very agitated, very annoyed and very pissed (and very anxious)".replace(/very/g, function($0) {
if (cnt === synonyms.length) cnt = 0;
return synonyms[cnt++]; //replace 5 matches of the keyword every with 5 synonyms in the array
}));
If you have more matches than there are items in the array, the cnt will make sure the array items will be used from the first one again.
A simple recursive approach. Be sure your synonyms array has enough elements to cover all matches in your string.
let synonyms = ["extremely", "exceedingly", "exceptionally"]
let yourString = "I'm very happy, very joyful, and very handsome."
let rex = /very/
function r (s, i) {
let newStr = s.replace(rex, synonyms[i])
if (newStr === s)
return s
return r(newStr, i+1)
}
r(yourString, 0)
I would caution that if your replacement would also match your regex, you need to add an additional check.
function replaceExpressionWithSynonymsInText(text, regX, synonymList) {
var
list = [];
function getSynonym() {
if (list.length <= 0) {
list = Array.from(synonymList);
}
return list.shift();
}
return text.replace(regX, getSynonym);
}
var
synonymList = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"],
textSource = "I'm very upset, very distress, very agitated, very annoyed and very pissed",
finalText = replaceExpressionWithSynonymsInText(textSource, (/very/g), synonymList);
console.log("synonymList : ", synonymList);
console.log("textSource : ", textSource);
console.log("finalText : ", finalText);
The advantages of the above approach are, firstly one does not alter the list of synonyms,
secondly working internally with an ever new copy of the provided list and shifting it,
makes additional counters obsolete and also provides the opportunity of being able to
shuffle the new copy (once it has been emptied), thus achieving a more random replacement.
Using the example you've provided, here's what I would do.
First I would set up some variables
var text = "I'm very upset, very distress, very agitated, very annoyed and very pissed";
var regex = /very/;
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
Then count the number of matches
var count = text.match(/very/g).length;
Then I would run a loop to replace the matches with the values from the array
for(var x = 0; x < count; x++) {
text = text.replace(regex, synonyms[x]);
}
You can do it with the use of Replace() function, where you use 'g' option for global matching (finds all occurrences of searched expression). For the second argument you can use a function which returns values from your predefined array.
Here is a little fiddle where you can try it out.
var str = "test test test";
var rep = ["one", "two", "three"];
var ix = 0;
var res = str.replace(/test/g, function() {
if (ix == rep.length)
ix = 0;
return rep[ix++];
});
$("#result").text(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="result">
Result...
</p>
Yes it is achievable. There may be a more efficient answer than this, but the brute force way is to double the length of your regex. i.e. Instead of searching just A, search (/A){optionalText}(/A) and then replace /1 /2 as needed. If you need help with the regex itself, provide some code for what you're searching for and someone with more rep than me can probably comment the actual regexp.

how to replace a char in string with many chars

I want to change a char in string with many values
I have string like this :
date_format = "%m/%d/%Y";
And i want to replace ever % with the char which after, so the date variable should be like this:
date_format="mm/dd/YY";
Here is what I tried so far, but i can't get it to work, so I need some help here:
function replaceon(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function locations(substring, string) {
var a = [],
i = -1;
while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
return a;
}
function corrent_format(date_format) {
var my_locations = locations('%', date_format);
console.log(my_locations.length);
for (var i = 0; i < my_locations.length; i++) {
replaceon(date_format, my_locations[i], date_format[my_locations[i] + 1]);
}
return date_format;
}
console.log(corrent_format(date_format));
You can try this:
"%m/%d/%Y".replace(/%([^%])/g,"$1$1")
Hope this hepls.
You can use a regular expression for that:
var date_format="%m/%d/%Y";
var res = date_format.replace(/%(.)/g, "$1$1");
console.log(res);
function act(str) {
var res = "";
for (var i = 0; i < (str.length - 1); i++) {
if (str[i] === "%")
res += str[i + 1];
else
res += str[i];
}
res += str[i];
return res;
}
var date_format = "%m/%d/%Y";
console.log(act(date_format));
Your code is not working because the date_format variable is not being modified by the corrent_format function. The replaceon function returns a new string. If you assign the result to date_format, you should get the expected result:
for (var i = 0; i < my_locations.length; i++) {
date_format = replaceon(date_format, my_locations[i], date_format[my_locations[i]+1])
}
Alternatively, you could perform the replacement using String.replace and a regular expression:
date_format.replace(/%(.)/g, '$1$1');
For the regex-challenged among us, here's a translation of /%(.)/g, '$1$1':
/ means that the next part is going to be regex.
% find a %.
. any single character, so %. would match %m, %d, and/or %Y.
(.) putting it in parens means to capture the value to use later on.
/g get all the matches in the source string (instead of just the first one).
?1 references the value we captured before in (.).
?1?1 repeat the captured value twice.
So, replace every %. with whatever's in the ., times two.
Now, this regex expression is the most concise and quickest way to do the job at hand. But maybe you can't use regular expressions. Maybe you have a dyslexic boss who has outlawed their use. (Dyslexia and regex are uneasy companions at best.) Maybe you haven't put in the 47 hours screaming at regular expressions that aren't doing what you want, that you're required to put in before you're allowed to use them. Or maybe you just hate regular expressions.
If any of these apply, you can also do this:
var x = '%m/%d/%y';
x = x.replace('%', 'm');
x = x.replace('%', 'd');
x = x.replace('%', 'y');
alert(x);
This takes advantage of the fact that the replace function only replaces the first match found.
But seriously, don't use this. Use regex. It's always better to invest that 20 hours working out a regex expression that condenses the 20 lines of code you wrote in 15 minutes down to one. Unless you have to get it done sometime tonight, and whatever you're trying just doesn't work, and it's getting close to midnight, and you're getting tired...well, no. Use regex. Really. Resist the temptation to avoid finding a regex solution. You'll be glad you did when you wake up at your desk in the morning, having missed your deadline, and get to go home and spend more time with your family, courtesy of your generous severance package.

Find all matches in a concatenated string of same-length words?

I have a long Javascript string with letters like :
"aapaalaakaaiartaxealpyaaraa"
This string is actually a chained list of 3-letter-words : "aap","aal","aak","aai", "art", "axe","alp", "yaa" and "raa"
In reality I have many of these strings, with different word lengths, and they can be up to 2000 words long, so I need the fastest way to get all the words that start with a certain string. So when searching for all words that start with "aa" it should return :
"aap","aal","aak" and "aai"
Is there a way to do this with a regex ? It's very important that it only matches on each 3-letter word, so matches in between words should not be counted, so "aar" should not be returned, and also not "yaa" or "raa".
The simple way:
var results = [];
for (var i = 0; i < str.length; i += 3) {
if (str.substring(i, i + 2) === "aa") {
results.push(str.substring(i, i + 3));
}
}
Don’t ask whether it’s the fastest – just check whether it’s fast enough, first. :)
How about:
var str = 'aapaalaakaaiartaxealpyaaraa';
var pattern = /^aa/;
var result = str.match(/.{3}/g).filter(function(word) {
return pattern.test(word);
});
console.log(result); //=> ["aap","aal","aak","aai"]
"aapaalaakaaiartaxealpyaaraa".replace(/\w{3}|\w+/g,function(m){return m.match(/^aa/)?m+',':','}).split(',').filter(Boolean)

Javascript - Splicing strings from certain character to next character

Hopefully a basic question, as I'm a bit lost where to begin.
Pretend we have this string in JS:
var foo = "Yes, today #hello #vcc #toomanyhashtags #test we went to the park and danced"
How would I go about dynamically finding the character "#" and removing everything after until it hits a space (or in the instance of #test, until the string ends)?
ie. So the above string would read:
var foo = "Yes, today we went to the park and danced "
I had the concept to loop through the entire strings' characters and if the character === "#", delete characters until the current loop's item === " ". Is there a shorter way to do this?
Preliminary Concept:
var foo = "Hello, this is my test #test #hello";
var stripHashtags = function(x) {
for (i=0; i < x.length; i++) {
if (x[i] !== "#") {
console.log(x[i]);
}
}
};
stripHashtags(foo);
You could also do it with a simple regex string
foo.replace(/#[^ ]*/g, ""))
foo.substr(0,foo.indexOf("#")). This can get you the required output i suppose if that's what you are looking for.
You could go about this using the indexOf() method available to strings. This returns the character location of the first occurrence of whatever you're looking for. Then use substring
var i = foo.indexOf('#');
foo = foo.substr(0,i);

Count the number of occurence of a case sensitive word in a paragraph in jquery

I want to count the number of occurrence of a specific words in a paragraph.
I am writing my code for key down event. I may have few hundreds words initially that may increase later on.
SO when the user is typing i will match the words in a paragraph and then get the number of occurrence. I also need to make sure that the match will be case sensitive.
Right now i am using this code:
$('.msg').val().split("AP").length - 1
Where AP is the keyword to match.
But i am not very happy with this.
Actually i have a list of few hundred keywords, how can i implement it efficiently.
Please note the words to match have spaces on both side i.e they are boundary words
Any help is appreciated
You can try something like the following:
var wordList = ["some", "word", "or", "other", "CASE", "Sensitive", "is", "required"],
wordCount = [];
for (var i=0; i < wordList.length; i++)
wordCount[i] = 0;
$("#someField").keyup(function(){
var i,
text = this.value,
re;
for (i = 0; i < wordList.length; i++) {
re = new RegExp("\\b" + wordList[i] + "\\b", "g");
wordCount[i] = 0;
while (re.test(text)) wordCount[i]++;
}
});
Demo: http://jsfiddle.net/zMdYg/2/ (updated with longer word list)
I don't really know what you want to do with the results, so I've just stuck them in a simple array, but you can see in the demo I then output them to the page so you can see it working. Obviously you'd substitute your own requirement in that part.
This is using a regex to test each word. You'll notice that with .split() or .indexOf() you'll get partial matches, e.g., if you look for "other" it will also match partway through "bother" (and so forth), but with the regex I've used \b to test on word boundaries.
For a large list of words you might want to create all the regexes in advance rather than redoing them on the fly in the loop, but it seemed to work fine for my simple test so I thought I wouldn't start doing premature optimisations. I'll leave that as an exercise for the reader...
If split() is not case-sensitive, then I would look at using indexOf(), which is case sensitive.
So maybe something like:
var words_array = ['one', 'two', 'three'];
var carot = 0;
var n_occurences = 0;
$.each(words_array, function(index, value){
while(carot < $('.msg').val().length && carot > -1){
carot = $('.msg').val().indexOf(' ' + words_array[index] + ' ', carot);
if (carot > -1){
n_occurences++;
}
}
});
I haven't tested this but I hope you get the idea.

Categories

Resources