Looking for more understanding on the replace method - javascript

I used this as a solution for a coderbyte exercise (longest word) I more or less read every line until I fully comprehended it and then copied it in I'm still not exactly sure how it works. The code is supposed to find the longest word in a sentence.
function LongestWord(sen) {
//this splits the string(sentence) into an array of words
var sentence = sen.split(" ");
var word = "";
var len = 0;
// code goes here
//this loops through the words split() from the sentence
for(var i = 0; i < sentence.length; i++) {
/*this part I don't fully understand if I'm right it replaces any letter a-z
regardless of case to "" */
var strip = sentence[i].replace(/[^a-zA-Z]/g, "");
if (strip.length > len) {
word = strip;
len = strip.length;
}
}
return word;
}
It is mainly the var strip section I'm not understanding. What happens when I call the replace method on sentence[i] and what is the reason for this?

This line var strip = sentence[i].replace(/[^a-zA-Z]/g, ""); will remove all characters that are not a letter.
[a-zA-Z] is a character class that contains all letters
[^a-zA-Z] is the negation of the precedent character class
g if for a global research (i.e. everywhere in the string)

/[^a-zA-Z]/
if at start of line there is a to z (small) A to Z (capital) found delete those characters

Related

How to join the string either with a dot, exclamation mark, or a question mark?

I want to convert a string to the sentence case. That is, uppercase the first character in each sentence and lowercase the following characters. I managed to do this. However, after splitting the string and converting it to a sentence case, I need to join it again with a corresponding character.
Here is my code that splits the string into sentences:
const string = "my seNTencE . My sentence! my another sentence. yEt another senTence? Again my sentence .";
function splitString(str) {
str = str.split(/[.!?]/);
for(let i = 0; i < str.length; i++) {
str[i] = str[i].trim();
}
for(let i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1).toLowerCase();
}
return str;
}
console.log(splitString(string));
In the return statement, I want to return joined strings. For example, the first sentence must end with a dot, and the second must end with an exclamation mark, etc. How to implement this?
str.split eliminates the result of the regex match from the string. If you want to keep it, you can place the separator in a lookbehind like this:
str.split(/(?<=[.!?])/);
The syntax (?<= ) means the regex will find positions that are preceded by punctuation, but won't include said punctuation in the match, so the split method will leave it in.
As a side note, keep in mind that this function will ruin acronyms, proper nouns, and the word I. Forcing the first letter after a period to be a capital letter is probably fine, but you will find that this function does more harm than good.
Use a regular expression with capture groups. This regex uses the lazy ? modifier so the match will end at the first [!.?], and the global g flag to grab all matches.
const string = "my seNTencE . My sentence! my another sentence. yEt another senTence? Again my sentence ."
const rx = /(.*?)([.!?])/g
const found = []
while (m = rx.exec(string)) {
let str = m[1].trim()
str = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
found.push(str + m[2])
}
console.log(found)

Write a method that takes in a sentence string and returns a new sentence representing its Aba translation

Beginner Coder and I'm confused if my include method is wrong. Maybe I should create an array and push the characters in? Am I on the right track?
Aba is a German children's game where secret messages are exchanged. In Aba, after every vowel we add "b" and add that same vowel. Write a method that takes in a sentence string and returns a new sentence representing its Aba translation. Capitalized words of the original sentence should be properly capitalized in the new sentence.
function abaTranslate(sentence) {
var words = sentence.split(" ");
const vowels = 'AEIOUaeiou';
var newStr = "";
var char = words[i];
for (var i = 0; i < sentence.length; i++) {
if (words.includes(vowels)) {
newStr += (words + "b")
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
You don't need to split your sentence into individual words, as you're not interested in looking at the words, but rather the individual characters in the sentence. With this in mind, you can use the current loop that you have, and for each i grab the current character from the input sentence at index i.
If the current character is a vowel (ie: if it is included in the vowels string), then you know the current character is a vowel, and so, you can add the current character separated by a "b" to your output string. Otherwise, it if its not a vowel, you can just add the current character to the output string.
See example below:
function abaTranslate(sentence) {
const vowels = 'AEIOUaeiou';
var newStr = "";
for (var i = 0; i < sentence.length; i++) {
var currentCharacter = sentence[i];
if (vowels.includes(currentCharacter)) { // the current character is a vowel
newStr += currentCharacter + "b" + currentCharacter;
} else {
newStr += currentCharacter; // just add the character if it is not a vowel
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
If you want to use JS methods to help you achieve this, you could use .replace() with a regular expression. Although, it's probably better to try and understand the above code before diving into regular expressions:
const abaTranslate = sentence => sentence.replace(/[aeiou]/ig, "$&b$&");
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"

Splitting a string by white space and a period when not surrounded by quotes

I know that similar questions have been asked many times, but my regular expression knowledge is pretty bad and I can't get it to work for my case.
So here is what I am trying to do:
I have a text and I want to separate the sentences. Each sentence ends with some white space and a period (there can be one or many spaces before the period, but there is always at least one).
At the beginning I used /\s+\./ and it worked great for separating the sentences, but then I noticed that there are cases such as this one:
"some text . some text".
Now, I don't want to separate the text in quotes. I searched and found a lot of solutions that work great for spaces (for example: /(".*?"|[^"\s]+)+(?=\s*|\s*$)/), but I was not able to modify them to separate by white space and a period.
Here is the code that I am using at the moment.
var regex = /\s+\./;
var result = regex.exec(fullText);
if(result == null) {
break;
}
var length = result[0].length;
var startingPoint = result.index;
var currentSentence = fullText.substring(0,startingPoint).trim();
fullText = fullText.substring(startingPoint+length);
I am separating the sentences one by one and removing them from the full text.
The length var represents the size of the portion that needs to be removed and startingPoint is the position on which the portion starts. The code is part of a larger while cycle.
Instead of splitting you may try and match all sentences between delimiters. In this case it will be easier to skip delimiters in quotes. The respective regex is:
(.*?(?:".*?".*?)?|.*?)(?: \.|$)
Demo: https://regex101.com/r/iS9fN6/1
The sentences then may be retrieved in this loop:
while (match = regex.exec(input)) {
console.log(match[1]); // each next sentence is in match[1]
}
BUT! This particular expression makes regex.exec(input) return true infinitely! (Looks like a candidate to one more SO question.)
So I can only suggest a workaround with removing the $ from the expression. This will cause the regex to miss the last part which later may be extracted as a trailer not matched by the regex:
var input = "some text . some text . \"some text . some text\" some text . some text";
//var regex = /(.*?(?:".*?".*?)?|.*?)(?: \.|$)/g;
var regex = /(.*?(?:".*?".*?)?|.*?) \./g;
var trailerPos = 0;
while (match = regex.exec(input)) {
console.log(match[1]); // each next sentence is in match[1]
trailerPos = match.index + match[0].length;
}
if (trailerPos < input.length) {
console.log(input.substring(trailerPos)); // the last sentence in
// input.substring(trailerPos)
}
Update:
If sentences span multiple lines, the regex won't work since . pattern does not match the newline character. In this case just use [\s\S] instead of .:
var input = "some \ntext . some text . \"some\n text . some text\" some text . so\nm\ne text";
var regex = /([\s\S]*?(?:"[\s\S]*?"[\s\S]*?)?|[\s\S]*?) \./g;
var trailerPos = 0;
var sentences = []
while (match = regex.exec(input)) {
sentences.push(match[1]);
trailerPos = match.index + match[0].length;
}
if (trailerPos < input.length) {
sentences.push(input.substring(trailerPos));
}
sentences.forEach(function(s) {
console.log("Sentence: -->%s<--", s);
});
Use the encode and decode of javascript while sending and receiving.

Detect repeating letter in an string in Javascript

code for detecting repeating letter in a string.
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string
JSFIDDLE
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.
Try this:
var str = "paraven4sr";
function checkDuplicate(str){
for(var i = 0; i < str.length; i++){
var re = new RegExp("[^"+ str[i] +"]","g");
if(str.replace(re, "").length >= 2){
return true;
}
}
return false;
}
alert(checkDuplicate(str));
Here is jsfiddle
To just test duplicate alphanumeric character (including underscore _):
console.log(/(\w)\1+/.test('aab'));
Something like this?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

Categories

Resources