Capitalize first letter in java script - javascript

I know this has been answered before, but I'm a newb and I can't get it to work in my situation. Basically, I have pages that call the URL and display part of them on the page. I am hoping to have the first letter of the displayed word capitalize automatically.
This is an example of what i'm using:
<script>
var str = (window.location.pathname);
var str2 = "/seedling/";
document.write(str.substr(str2.length,(str.length - str2.length - 1 ) ) );
</script>
Thanks so much for your help, it is much appreciated!!

You can capitalise the first letter of a string like this:
var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);
Alternatively:
var capitalised = yourString.charAt(0).toUpperCase() + yourString.substring(1);
Assuming that your document.write call contains the string you want to capitalise:
var yourString = str.substr(str2.length,(str.length - str2.length - 1 ) );
var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);

If you have LoDash on hand, this can also be achieved using _.capitalize
_.capitalize('FRED');
// => 'Fred'

Related

JavaScript split but keep last character in succinct way

I have a string that may or may not have a period and if it does I want to split on that and then add the period back. This is the code I have
let blurb = body.split('.')[0];
if (blurb.length > 1) {
blurb = blurb + '.';
}
I was hoping there is a more succinct and clear way to do this.
If you really just want to add it back without doing anything else...
let blurb = body.split('.').join('.');
But this is a no-op. Here's an obtuse version of your code, which may help clarify some things..
var body = "Some sentences. In a paragraph.",
bodySplit = body.split('.'), // ["Some sentences"," In a paragraph", ""],
firstSentence = bodySplit[0],
firstSentenceHasChars = firstSentence.length > 1,
blurb = null;
if (firstSentenceHasChars) {
blurb = firstSentence + ".";
} else {
// ?
}
Well you can use split with number of desired match in output as second parameter ( second parameter in split specifies number of splited element desired in output in our case you can add as 1 ).
console.log( 'blah.blah'.split('.', 1)[0] + '.' )
console.log( 'blahblah'.split('.', 1)[0] + '.' )
Here is a way to do it with String.replace() and a regex. You simply replace a dot followed by anything by a dot.
const dot = str => str.replace(/\..*$/, '.');
console.log(dot('hello. world'));
console.log(dot('bye bye.'));
console.log(dot('no dot here'));
I know this isn't everyone's cup of tea, but I went the regex route. This might make you ill though:
var str = 'blah.blah';
var reg = /([a-z]+)(.?)([a-z]*)/;
var arr = str.replace(reg, "$1,$3,$2").split(",").filter(s => s);
console.log(arr);
str = 'blahblah';
arr = str.replace(reg, "$1,$3,$2").split(",").filter(s => s);
console.log(arr);
I don't know where you want to go with this but I'd do:
"hohohosdsaeqwewe.kekekekekeke".replace(/([^.]*)\.([^.]*)/gi,(m,g1)=>g1+".")
if the sentence does not have any match, returns itself, if it does, then takes the first part(before the dot) and adds the dot back.

jquery/javascript how to get rid of blank spaces (replace() not working)

Hi all,
I have a string coming from my database:
var theString = "LNDSH - LONDON SHOPS";
I need to get two variables out of it.
One with the code before the -, and the other one with the sentence after the -.
To do so I do:
var sentence = $.trim(theString.substring((theString.indexOf('-')+1),theString.length));
var code = $.trim(theString.substring(0, theString.indexOf('-')));
var sentence is ok, but I cannot get rid of the spaces before the - in the code variable.
I really need to get rid of those spaces.
Please note that in var sentence I'm doing +1 because it is always one space in between the sentence and the -.
But in the case of the code: I don't know the length of the code and I don't know how many spaces will be before the -
I've tried:
code.replaceAll("\\s+", " ");
But this does not show a thing in my page (no javascript errors either).
I'm using jquery-1.5.1.min and jquery-ui-1.8.14.custom.min
Thanks a lot!
You may use split with regular expression:
var values = "LNDSH - LONDON SHOPS".split(/\s*-\s*/);
console.log(values[0]); // "LNDSH"
console.log(values[1]); // "LONDON SHOPS"
Try this:
variable.replace(/\s/g,'');
Edit: The above will not seperate your strings, it will only remove the white spaces.
To seperate the strings you can do this:
var seperate = theString.split("-", 2);
var LNDSH = seperate[0];
var LONDON_SHOPS = seperate[1];
var theString = "LNDSH - LONDON SHOPS";
var vett = theString.split("-");
var a = vett[0].trim();
var b = vett[1].trim();
var test = theString.split("-");
alert(test[0].trim());
alert(test[1].trim());

Change occurrences of sum(something) to something_sum

Admittedly I'm terrible with RegEx and pattern replacements, so I'm wondering if anyone can help me out with this one as I've been trying now for a few hours and in the process of pulling my hair out.
Examples:
sum(Sales) needs to be converted to Sales_sum
max(Sales) needs to be converted to Sales_max
min(Revenue) needs to be converted to Revenue_min
The only available prefixed words will be sum, min, max, avg, xcount - not sure if this makes a difference in the solution.
Hopefully that's enough information to kind of show what I'm trying to do. Is this possible via RegEx?
Thanks in advance.
There are a few possible ways, for example :
var str = "min(Revenue)";
var arr = str.match(/([^(]+)\(([^)]+)/);
var result = arr[2]+'_'+arr[1];
result is then "Revenue_min".
Here's a more complex example following your comment, handling many matches and lowercasing the verb :
var str = "SUM(Sales) + MIN(Revenue)";
var result = str.replace(/\b([^()]+)\(([^()]+)\)/g, function(_,a,b){
return b+'_'+a.toLowerCase()
});
Result : "Sales_sum + Revenue_min"
Try with:
var input = 'sum(Sales)',
matches = input.match(/^([^(]*)\(([^)]*)/),
output = matches[2] + '_' + matches[1];
console.log(output); // Sales_sum
Also:
var input = 'sum(Sales)',
output = input.replace(/^([^(]*)\(([^)]*)\)/, '$2_$1');
You can use replace with tokens:
'sum(Sales)'.replace(/(\w+)\((\w+)\)/, '$2_$1')
Using a whitelist for your list of prefixed words:
output = input.replace(/\b(sum|min|max|avg|xcount)\((.*?)\)/gi,function(_,a,b) {
return b.toLowerCase()+"_"+a;
});
Added \b, a word boundary. This prevents something like "haxcount(xorz)" from becoming "haxorz_xcount"

Add line breaks after n numbers of letters in long words

A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:
aaaaaaaaaaaaaaaaaaaaaaaaa
Should turn in to
aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa
I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks
Here is one option:
string.match(/.{1,10}/g).join("<br/>");
Assuming the text is inside a div or a span:
<div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div>
You can do:
$(function() {
var html=$('#myDiv').html();
var newHtml='';
for (var i=0;i<html.length;i++) {
newHtml=newHtml+html[i];
if ((i+1)%10==0) {newHtml=newHtml+'<br/>';}
}
$('#myDiv').html(newHtml);
});
Here is example: http://jsfiddle.net/68PvB/
Good Luck!
If you have your string in a variable you can use its replace method like this:
var chunklen = 2; //the length of the chunks you require
var str = '123456789'; //your string
var rxp = new RegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories