Capitalize Words After Each dot (.) & Starting of a String - javascript

How to capitalize each words on starting of a string and after dot(.) sign?
I made a research on google and stackoverflow, below are the codes that I achieved but this will only capitalize starting of a string. Example as belows;
var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());
document.write(str);
I want the string to be This is a text. Hello world!.
I have tried to use css, text-transform: capitalize; but this will result in each word to be capitalize.

I use a function like this, that takes an optional second parameter that will convert the entire string to lowercase initially. The reason is that sometimes you have a series of Title Case Items. That You Wish to turn into a series of Title case items. That you wish to have as sentence case.
function sentenceCase(input, lowercaseBefore) {
input = ( input === undefined || input === null ) ? '' : input;
if (lowercaseBefore) { input = input.toLowerCase(); }
return input.toString().replace( /(^|\. *)([a-z])/g, function(match, separator, char) {
return separator + char.toUpperCase();
});
}
The regex works as follows
1st Capturing Group (^|\. *)
1st Alternative ^
^ asserts position at start of the string
2nd Alternative \. *
\. matches the character `.` literally (case sensitive)
* matches the character ` ` literally (case sensitive)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([a-z])
Match a single character present in the list below [a-z]
a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)
You would implement it in your example like so:
var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!
Example jsfiddle
PS. in future, i find regex101 a hugely helpful tool for understanding and testing regex's

If you are using jquery, use this code
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var str = "my name is Jhon. are you good. is it";
var str1 = str.split('.');
var str2 = "";
$.each(str1,function(i){
str2 += capitalize($.trim(str1[i]))+'. ';
});
console.log(str2);
catch the out put in str2.
in my case its like the following.
My name is Jhon. Are you good. Is it.

Related

Is there a javascript method to recognize a string even if the words are out of order? [duplicate]

I would like to find all the matches of given strings (divided by spaces) in a string.
(The way for example, iTunes search box works).
That, for example, both "ab de" and "de ab" will return true on "abcde" (also "bc e a" or any order should return true)
If I replace the white space with a wild card, "ab*de" would return true on "abcde", but not "de*ab".
[I use * and not Regex syntax just for this explanation]
I could not find any pure Regex solution for that.
The only solution I could think of is spliting the search term and run multiple Regex.
Is it possible to find a pure Regex expression that will cover all these options ?
Returns true when all parts (divided by , or ' ') of a searchString occur in text. Otherwise false is returned.
filter(text, searchString) {
const regexStr = '(?=.*' + searchString.split(/\,|\s/).join(')(?=.*') + ')';
const searchRegEx = new RegExp(regexStr, 'gi');
return text.match(searchRegEx) !== null;
}
I'm pretty sure you could come up with a regex to do what you want, but it may not be the most efficient approach.
For example, the regex pattern (?=.*bc)(?=.*e)(?=.*a) will match any string that contains bc, e, and a.
var isMatch = 'abcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals true
var isMatch = 'bcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals false
You could write a function to dynamically create an expression based on your search terms, but whether it's the best way to accomplish what you are doing is another question.
Alternations are order insensitive:
"abcde".match(/(ab|de)/g); // => ['ab', 'de']
"abcde".match(/(de|ab)/g); // => ['ab', 'de']
So if you have a list of words to match you can build a regex with an alternation on the fly like so:
function regexForWordList(words) {
return new RegExp('(' + words.join('|') + ')', 'g');
}
'abcde'.match(['a', 'e']); // => ['a', 'e']
Try this:
var str = "your string";
str = str.split( " " );
for( var i = 0 ; i < str.length ; i++ ){
// your regexp match
}
This is script which I use - it works also with single word searchStrings
var what="test string with search cool word";
var searchString="search word";
var search = new RegExp(searchString, "gi"); // one-word searching
// multiple search words
if(searchString.indexOf(' ') != -1) {
search="";
var words=searchString.split(" ");
for(var i = 0; i < words.length; i++) {
search+="(?=.*" + words[i] + ")";
}
search = new RegExp(search + ".+", "gi");
}
if(search.test(what)) {
// found
} else {
// notfound
}
I assume you are matching words, or parts of words. You want space-separated search terms to limit search results, and it seems you intend to return only those entries which have all the words that the user supplies. And you intend a wildcard character * to stand for 0 or more characters in a matching word.
For example, if the user searches for the words term1 term2, you intend to return only those items which have both words term1 and term2. If the user searches for the word term*, it would match any word beginning with term.
There are suitable regular expressions which are equivalent to this search language and can be generated from it.
A simple example, the word term, can be asserted in regex by converting to \bterm\b. But two or more words which must match in any order require lookahead assertions. Using extended syntax, the equivalent regex is:
(?= .* \b term1 \b )
(?= .* \b term2 \b )
The asterisk wildcard can be asserted in regex with a character class followed by asterisk. The character class identifies which letters you consider to be part of word. For example, you might find that [A-Za-z0-9]* fits the bill.
In short, you might be satisfied if you convert an expression such as:
foo ba* quux
to:
(?= .* \b foo \b )
(?= .* \b ba[A-Za-z0-9]* \b )
(?= .* \b quux \b )
That is a simple matter of search and replace. But do be careful to sanitize the input string to avoid injection attacks by removing punctuation, etc.
I think you may be barking up the wrong tree with RegEx. What you might want to look at is the Levenshtein distance of two input strings.
There's a Javascript implementation here and a usage example here.

Non-capturing group matching whitespace boundaries in JavaScript regex

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;
};

regex to remove number (year only) from string

I know the regex that separates two words as following:
input:
'WonderWorld'
output:
'Wonder World'
"WonderWorld".replace(/([A-Z])/g, ' $1');
Now I am looking to remove number in year format from string, what changes should be done in the above code to get:
input
'WonderWorld 2016'
output
'Wonder World'
You can match the location before an uppercase letter (but excluding the beginning of a line) with \B(?=[A-Z]) and match the trailing spaces if any with 4 digits right before the end (\s*\b\d{4}\b). In a callback, check if the match is not empty, and replace accordingly. If a match is empty, we matched the location before an uppercase letter (=> replace with a space) and if not, we matched the year at the end (=> replace with empty string). The four digit chunks are only matched as whole words due to the \b word boundaries around the \d{4}.
var re = /\B(?=[A-Z])|\s*\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match) {
return match ? "" : " ";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
A similar approach, just a different pattern for matching glued words (might turn out more reliable):
var re = /([a-z])(?=[A-Z])|\s*\b\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match, group1) {
return group1 ? group1 + " " : "";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
Here, ([a-z])(?=[A-Z]) matches and captures into Group 1 a lowercase letter that is followed with an uppercase one, and inside the callback, we check if Group 1 matched (with group1 ?). If it matched, we return the group1 + a space. If not, we matched the year at the end, and remove it.
Try this:
"WonderWorld 2016".replace(/([A-Z])|\b[0-9]{4}\b/g, ' $1')
How about this, a single regex to do what you want:
"WonderWorld 2016".replace(/([A-Z][a-z]+)([A-Z].*)\s.*/g, '$1 $2');
"Wonder World"
get everything apart from digits and spaces.
re-code of #Wiktor Stribiżew's solution:
str can be any "WonderWorld 2016" | "OneTwo 1000 ThreeFour" | "Ruby 1999 IamOnline"
str.replace(/([a-z])(?=[A-Z])|\s*\d{4}\b/g, function(m, g) {
return g ? g + " " : "";
});
import re
remove_year_regex = re.compile(r"[0-9]{4}")
Test regex expression here

Cannot get all possible overlapping regular expression matches

I have string
Started: 11.11.2014 11:19:28.376<br/>Ended: 1.1.4<br/>1:9:8.378<br/>Request took: 0:0:0.2
I need to add zeros in case I encounter 1:1:8 it should be 01:01:08 same goes for date. I tried using
/((:|\.|\s)[0-9](:|\.))/g
but it did not give all possible overlapping matches. How to fix it?
var str = "Started: 11.11.2014 11:19:28.376<br/>Ended: 11.11.2014<br/>11:19:28.378<br/>Request took: 0:0:0.2";
var re = /((:|\.|\s)[0-9](:|\.))/g
while ((match = re.exec(str)) != null) {
//alert("match found at " + match.index);
str = [str.slice(0,match.index), '0', str.slice(match.index+1,str.length)];
}
alert(str);
This will probably do what you want:
str.replace(/\b\d\b/g, "0$&")
It searches for lone digits \d, and pad 0 in front.
The first word boundary \b checks that there is no [a-zA-Z0-9_] in front, and the second checks there is no [a-zA-Z0-9_] behind the digit.
$& in the replacement string refers to the whole match.
If you want to pad 0 as long as the character before and after are not digits:
str.replace(/(^|\D)(\d)(?!\d)/g, "$10$2")

How to make first character uppercase of all words in JavaScript?

I have searched for solution but did not find yet.
I have the following string.
1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World
I want to convert them to following:
1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld
If there is No space and underscore in string just uppercase first and all others to lowercase. If words are separated by underscore or space then Uppercase first letter of each word and remove space and underscore. How can I do this in JavaScript.
Thanks
Here is a regex solution:
First lowercase the string:
str = str.toLowerCase();
Replace all _ and spaces and first characters in a word with upper case character:
str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})
DEMO
Update: Less steps ;)
Explanation:
/ // start of regex
(?: // starts a non capturing group
_| |\b // match underscore, space, or any other word boundary character
// (which in the end is only the beginning of the string ^)
) // end of group
( // start capturing group
\w // match word character
) // end of group
/g // and of regex and search the whole string
The value of the capturing group is available as p1 in the function, and the whole expression is replaced by the return value of the function.
You could do something like this:
function toPascalCase(str) {
var arr = str.split(/\s|_/);
for(var i=0,l=arr.length; i<l; i++) {
arr[i] = arr[i].substr(0,1).toUpperCase() +
(arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
}
return arr.join("");
}
You can test it out here, the approach is pretty simple, .split() the string into an array when finding either whitespace or an underscore. Then loop through the array, upper-casing the first letter, lower-casing the rest...then take that array of title-case words and .join() it together into one string again.
function foo(str) {
return $(str.split(/\s|_/)).map(function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}).get().join("");
}
Working demo: http://jsfiddle.net/KSJe3/3/
(I used Nicks regular expression in the demo)
Edit: Another version of the code - I replaced map() with $.map():
function foo(str) {
return $.map(str.split(/\s|_/), function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join("");
}
Working demo: http://jsfiddle.net/KSJe3/4/
An ES6 / functional update of #NickCraver's answer. As with #NickCraver's answer this function will handle multiple spaces / underscores properly by filtering them out.
const pascalWord = x => x[0].toUpperCase() + x.slice(1).toLowerCase();
const toPascalCase2 = (str) => (
str.split(/\s|_/)
.filter(x => x)
.map(pascalWord)
.join('')
);
const tests = [
'hello',
'HELLO',
'hello_world',
'HELLO_WORLD',
'Hello World',
'HELLO__WORLD__',
'Hello World_',
].map(toPascalCase2).join('<br>');
document.write(tests);
var city = city.replace(/\s+/g,' ') //replace all spaceses to singele speace
city = city.replace(/\b\w/g,city => city .toUpperCase()) //after speace letter convert capital

Categories