capitalize first letter of word more than 3 character Regex - javascript

I code something in React and i want to use Regex to capitalize first letter of word more than 3 letters with Regex, but I'am lost with Regex, i found lot of things but nothings works. Any advice?
Regex example but dont work
"^[a-z](?=[a-zA-Z'-]{3})|\b[a-zA-Z](?=[a-zA-Z'-]{3,}$)|['-][a-z]"

\w{4,} - this regex expression will match all words that have more than 3 letters
let str = "this is Just an long string with long and short words";
const matches = str.matchAll(/\w{4,}/g);
for(match of matches) {
str = str.substring(0, match.index) + match[0].charAt(0).toUpperCase() + match[0].slice(1) + str.substring(match.index + match[0].length);
}
console.log(str);

Here are two example. One for sentences (like AidOnline01's answer, but using String#replaceAll) and a second one when using words only.
However, when using words only, you can also check for the length instead of using a regexp.
const sentence = "This is a sentence with a few words which should be capitialized";
const word = "capitialized";
// use String#replaceAll to replace all words in a sentence
const sentenceResult = sentence.replaceAll(/\w{4,}/g, word => word[0].toUpperCase() + word.slice(1));
// use String#replace for a single word
const wordResult = word.replace(/\w{4,}/, word => word[0].toUpperCase() + word.slice(1));
console.log(sentenceResult);
console.log(wordResult);

Related

Regex match apostrophe inside, but not around words, inside a character set

I'm counting how many times different words appear in a text using Regular Expressions in JavaScript. My problem is when I have quoted words: 'word' should be counted simply as word (without the quotes, otherwise they'll behave as two different words), while it's should be counted as a whole word.
(?<=\w)(')(?=\w)
This regex can identify apostrophes inside, but not around words. Problem is, I can't use it inside a character set such as [\w]+.
(?<=\w)(')(?=\w)|[\w]+
Will count it's a 'miracle' of nature as 7 words, instead of 5 (it, ', s becoming 3 different words). Also, the third word should be selected simply as miracle, and not as 'miracle'.
To make things even more complicated, I need to capture diacritics too, so I'm using [A-Za-zÀ-ÖØ-öø-ÿ] instead of \w.
How can I accomplish that?
1) You can simply use /[^\s]+/g regex
const str = `it's a 'miracle' of nature`;
const result = str.match(/[^\s]+/g);
console.log(result.length);
console.log(result);
2) If you are calculating total number of words in a string then you can also use split as:
const str = `it's a 'miracle' of nature`;
const result = str.split(/\s+/);
console.log(result.length);
console.log(result);
3) If you want a word without quote at the starting and at the end then you can do as:
const str = `it's a 'miracle' of nature`;
const result = str.match(/[^\s]+/g).map((s) => {
s = s[0] === "'" ? s.slice(1) : s;
s = s[s.length - 1] === "'" ? s.slice(0, -1) : s;
return s;
});
console.log(result.length);
console.log(result);
You might use an alternation with 2 capture groups, and then check for the values of those groups.
(?<!\S)'(\S+)'(?!\S)|(\S+)
(?<!\S)' Negative lookbehind, assert a whitespace boundary to the left and match '
(\S+) Capture group 1, match 1+ non whitespace chars
'(?!\S) Match ' and assert a whitespace boundary to the right
| Or
(\S+) Capture group 2, match 1+ non whitespace chars
See a regex demo.
const regex = /(?<!\S)'(\S+)'(?!\S)|(\S+)/g;
const s = "it's a 'miracle' of nature";
Array.from(s.matchAll(regex), m => {
if (m[1]) console.log(m[1])
if (m[2]) console.log(m[2])
});

How to Capitalize first word of Every Sentence in JavaScript

I want the first letter of all sentences in uppercase using JavaScript, like after every full stop (.) the first character is in Uppercase.
Like this:
This is the first sentence. This is the second sentence. This is the third sentence
The following code should work to a good measure:
text = text.replace(/(\.\s)([a-z])/g, (_, punctuation, char) => {
return punctuation + char.toUpperCase();
});
A regex expression is used with two capturing groups, and String.prototype.replace is used with a replace function.
const txt = "this is the first sentence. this is the second sentence. this is the third sentence";
const _txt = txt.split('.'); // split the the text into array by "."
const _finalText = [];
for(const tx of _txt) { //loop through the array
const _tx = tx.trim(); //trim the element since some will contain space.
const fl = _tx[0].toUpperCase(); //take the first character of the sentence and capitalize it.
_finalText.push(fl+_tx.substr(1)) //push the result of the concatenation of the first letter(fl) and remaining letters without the first letter into the array;
}
console.log(_finalText.join('. ')) // This is the first sentence. This is the second sentence. This is the third sentence
let mySentences = "this is the first sentence. this is the second sentence. this is the third sentence"
let newSentences = "";
// You can use this simple code
mySentences.split(".").map(elem => newSentences += (elem.trim().charAt(0).toUpperCase() + elem.trim().slice(1, elem.length) + "."))
console.log(newSentences)

jQuery autocomplete RegExp for highlight words [duplicate]

I have this function that finds whole words and should replace them. It identifies spaces but should not replace them, ie, not capture them.
function asd (sentence, word) {
str = sentence.replace(new RegExp('(?:^|\\s)' + word + '(?:$|\\s)'), "*****");
return str;
};
Then I have the following strings:
var sentence = "ich mag Äpfel";
var word = "Äpfel";
The result should be something like:
"ich mag *****"
and NOT:
"ich mag*****"
I'm getting the latter.
How can I make it so that it identifies the space but ignores it when replacing the word?
At first this may seem like a duplicate but I did not find an answer to this question, that's why I'm asking it.
Thank you
You should put back the matched whitespaces by using a capturing group (rather than a non-capturing one) with a replacement backreference in the replacement pattern, and you may also leverage a lookahead for the right whitespace boundary, which is handy in case of consecutive matches:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word + '(?=$|\\s)'), "$1*****");
return str;
};
var sentence = "ich mag Äpfel";
var word = "Äpfel";
console.log(asd(sentence, word));
See the regex demo.
Details
(^|\s) - Group 1 (later referred to with the help of a $1 placeholder in the replacement pattern): a capturing group that matches either start of string or a whitespace
Äpfel - a search word
(?=$|\s) - a positive lookahead that requires the end of string or whitespace immediately to the right of the current location.
NOTE: If the word can contain special regex metacharacters, escape them:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '(?=$|\\s)'), "$1*****");
return str;
};

Javascript - How to join two capitalize first letter of word scripts

I have an Acrobat form with some text fields with multiline on. My goal is to convert to uppercase the first letter of any sentence (look for dots) and also the first letter of any new line (after return has been pressed).
I can run each transformation separately, but do not know how to run them together.
To capitalize sentences I use the following code as custom convalidation :
// make an array split at dot
var aInput = event.value.split(". ");
var sCharacter = '';
var sWord='';
// for each element of word array, capitalize the first letter
for(i = 0; i <aInput.length; i++)
{
aInput[i] = aInput[i].substr(0, 1).toUpperCase() + aInput[i].substr(1) .toLowerCase();
}
// rebuild input string with modified words with dots
event.value = aInput.join('. ');
To capitalize new lines I replace ". " with "\r".
Thanks in advance for any help.
You can get the first character of each sentence with RegExp :
event.value = event.value.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
Demo : http://jsfiddle.net/00kzc370/
Regular Expression explained :
/.+?[\.\?\!](\s|$)/g is a regular expression.
.+?[\.\?\!](\s|$) is a pattern (to be used in a search) that match sentences ended by ., ? or ! and followed by a whitespace character.
g is a modifier. (Perform a global match (find all matches rather than stopping after the first match)).
Source : http://www.w3schools.com/jsref/jsref_obj_regexp.asp

How can I take a word from a text and make it into a link?

<script>
function myClick(){
text = "<b><i>this is my text, THIS NEEDS TO BE A HYPERLINK </i></b>";
document.getElementById('heading1').innerHTML = document.getElementById('heading1').innerHTML + text;
document.getElementById("heading1").style.textAlign="left";
document.getElementById("heading1").style.marginLeft="5px";
}
</script>
I only want the capital letters to be a hyperlink, it seems really easy but i cant find an answer online. (-.-)
Something like this would do it
var text = "<b><i>this is my text, THIS NEEDS TO BE A HYPERLINK </i></b>";
// Regex matching only uppercase letters and whitespaces where there
// have to be at least 2 in a row to match
var match = text.match(/[A-Z\s]{2,}/);
if (match && match.length) {
match.forEach(function (str) {
text = text.replace(str, '' + str + '');
});
}
EDIT:
When you want to only replace a single word you can omit the \s group in the regex:
This regex still matches at minimum two uppercase characters to prevent misdetection of capitalized words or names.
var match = text.match(/[A-Z]{2,}/);

Categories

Resources