What is an acceptable way to remove a particular trailing character from a string?
For example if I had a string:
> "item,"
And I wanted to remove trailing ','s only if they were ','s?
Thanks!
Use a simple regular expression:
var s = "item,";
s = s.replace(/,+$/, "");
if(myStr.charAt( myStr.length-1 ) == ",") {
myStr = myStr.slice(0, -1)
}
A function to trim any trailing characters would be:
function trimTrailingChars(s, charToTrim) {
var regExp = new RegExp(charToTrim + "+$");
var result = s.replace(regExp, "");
return result;
}
function test(input, charToTrim) {
var output = trimTrailingChars(input, charToTrim);
console.log('input:\n' + input);
console.log('output:\n' + output);
console.log('\n');
}
test('test////', '/');
test('///te/st//', '/');
This will remove trailing non-alphanumeric characters.
const examples = ["abc", "abc.", "...abc", ".abc1..!##", "ab12.c"];
examples.forEach(ex => console.log(ex.replace(/\W+$/, "")));
// Output:
abc
abc
...abc
.abc1
ab12.c
Related
I'm trying to generate a link using jQuery and need to trim the last '+' sign off the end. Is there a way to detect if there is one there, and then trim it off?
So far the code removes the word 'hotel' and replaces spaces with '+', I think I just need another replace for the '+' that shows up sometimes but not sure how to be super specific with it.
var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");
The answer to
What is the regex to remove last + sign from a string
is this
const str = "Hotel+"
const re = /\+$/; // remove the last plus if present. $ is "end of string"
console.log(str.replace(re,""))
The question is however if this is answering the actual problem at hand
If you have the string
"Ritz Hotel"
and you want to have
https://www.ritz.com
then you could trim the string:
const fullName = "Ritz Hotel",
name = fullName.replace("Hotel", "").trim().toLowerCase(),
link = `https://www.${name}.com`;
console.log(link)
// or if you want spaces to be converted in url safe format
const fullName1 = "The Ritz Hotel",
name1 = fullName1.replace("Hotel", "").trim().toLowerCase(),
link1 = new URL(`https://www.hotels.com/search?${name1}`).toString()
console.log(link1)
As an alternative to mplungjan's answer, you can use str.endsWith() for the check. If it ends on the + it will be cut out. There is no need for regex. If you can avoid regex you definitely should.
let str = "Hotel+";
if (str.endsWith("+")) {
str = str.substr(0, str.length - 1);
}
console.log(str);
Below you can find a function to replace all the whitespace characters with + excluding the last one:
const raw = "My Ho te l ";
function replaceSpacesWithPlus(raw) {
let rawArray = Array.from(raw);
let replArray = [];
for (let i = 0; i < rawArray.length; i++) {
const char = rawArray[i];
// handle characters 0 to n-1
if (i < rawArray.length - 1) {
if (char === ' ') {
replArray.push('+');
} else {
replArray.push(char);
}
} else {
// handle last char
if (char !== ' ' && char !== '+') {
replArray.push(char);
}
}
}
return replArray;
}
console.log(replaceSpacesWithPlus(raw));
The below snippet will remove all the existing + symbols from string.
let str = 'abcd + efg + hij';
str = str.replace(/\+/gm, '');
//output: abcd efg hij
For trim use the below snippet. It will remove the spaces from around the string.
let str = " Hello World!! "
str = str.trim();
// output: Hello World!!
If you want to replace the last + symbol only.
let str = 'abcd + efg + hij';
let lastIndex = str.lastIndexOf('+');
if (lastIndex > -1) {
let nextString = str.split('');
nextString.splice(lastIndex, 1, '');
str = nextString.join('');
}
// output: abcd + efg hij
How to replace or convert $ 10.000,00 into number 10000 without $ in the beginning and ,00 in the end in Javascript?
I would do it using regex replaces:
var input = "$ 10.000,00";
var output = input
.replace(/,.*/g, '') // cut off ',' and after
.replace(/\D/g, ''); // remove non-digit characters
// or in one go:
// var output = input.replace(/,.*|\D/g, '');
output = parseInt(output, 10); // convert to Number
console.log(output); // 10000
Here you go, could be done easily though.
let price = "$ 10.000,00"
price = parseInt(price.split('.').join("").replace(/\$/g,'')).toFixed(0)
console.log(price)
You can try string replace.
let str = "$ 10.000,00";
// swap the places for , and .
let newstr = str.replace(/[.,]/g, ($1) => {
return $1 === '.' ? ',' : '.'
})
let num = newstr.replace(/[$,]/g, "");
console.log(num)
console.log(Number(num)) // convert it into number
console.log(parseFloat(num)) // or this
Support for more entries:
const toNumber = n => parseFloat(n.replace(/(?:^\D+)?(\d+)\.(\d{3})(,(\d+))?/, "$1$2.$4"))
console.log(toNumber("$ 10.000,00"))
console.log(toNumber("$ 10.000,69"))
console.log(toNumber("$ 10.000,00"))
console.log(toNumber("10.050,00"))
console.log(toNumber("10.981"))
I would like to know how to capitalize the first letter after hypen in a string using javascript. If no hypen str should in lowercase
var result = capitalize("js-script");
function capitalize(str){
return str.split("-")[1].charAt(0).toUpperCase()+ str.slice(1);
}
Expected Output:
js-script => js-Script
tom => tom
Consider using a regular expression instead - match a - and an alphabetical character, and replace with a - and that word character, capitalized:
const capitalize = (str) => str.replace(/-([a-z])/g, (_, char) => '-' + char.toUpperCase());
console.log(capitalize("js-script"));
console.log(capitalize("foo-bar-baz"));
To fix your original code, if there's only going to be one - in the input, you need to save the rest of the characters in the part after the - (not just the charAt(0)):
function capitalize(str) {
if (!str.includes('-')) {
return str;
}
const [before, after] = str.split("-");
return before + '-' + after.charAt(0).toUpperCase() + after.slice(1);
}
console.log(capitalize('foo-bar'));
console.log(capitalize('foo'));
You can use regex and look behind to do this:
console.log(capitalize("js-script"));
function capitalize(str){
return str.replace(/(?<=-)\w/g, (text) => text.toUpperCase());
}
You can simply use regex and replace method
-[a-z]
- - match character -
[a-z] - match any character from a to z
function capitalize(str){
return typeof str === 'string' ? str.replace(/-([a-z])/gi,(m,g1)=> `-${g1.toUpperCase()}`) : str
}
console.log(capitalize("js-script"))
console.log( capitalize("tom"))
You can do this,
function capitalize(str){
let arrSplit = str.split("-")
let joinArray = [];
for(var i=0;i<arrSplit.length;i++){
if(i==0){
joinArray.push(arrSplit[i]);
}else{
joinArray.push(arrSplit[i].charAt(0).toUpperCase()+arrSplit[i].slice(1));
}
}
return joinArray.join("-",)
}
console.log(capitalize("js-script"))
console.log(capitalize("js-script-again"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Im trying to replace a character at a specific indexOf to uppercase.
My string is a surname plus the first letter in the last name,
looking like this: "lovisa t".
I check the position with this and it gives me the right place in the string. So the second gives me 8(in this case).
first = texten.indexOf(" ");
second = texten.indexOf(" ", first + 1);
And with this I replace the first letter to uppercase.
var name = texten.substring(0, second);
name=name.replace(/^./, name[0].toUpperCase());
But how do I replace the character at "second" to uppercase?
I tested with
name=name.replace(/.$/, name[second].toUpperCase());
But it did´t work, so any input really appreciated, thanks.
Your error is the second letter isn't in position 8, but 7.
Also this second = texten.indexOf(" ", first + 1); gives -1, not 8, because you do not have a two spaces in your string.
If you know that the string is always in the format surname space oneLetter and you want to capitalize the first letter and the last letter you can simply do this:
var name = 'something s';
name = name[0].toUpperCase() + name.substring(1, name.length - 1) + name[name.length -1].toUpperCase();
console.log(name)
Here's a version that does exactly what your question title asks for: It uppercases a specific index in a string.
function upperCaseAt(str, i) {
return str.substr(0, i) + str.charAt(i).toUpperCase() + str.substr(i + 1);
}
var str = 'lovisa t';
var i = str.indexOf(' ');
console.log(upperCaseAt(str, i + 1));
However, if you want to look for specific patterns in the string, you don't need to deal with indices.
var str = 'lovisa t';
console.log(str.replace(/.$/, function (m0) { return m0.toUpperCase(); }));
This version uses a regex to find the last character in a string and a replacement function to uppercase the match.
var str = 'lovisa t';
console.log(str.replace(/ [a-z]/, function (m0) { return m0.toUpperCase(); }));
This version is similar but instead of looking for the last character, it looks for a space followed by a lowercase letter.
var str = 'lovisa t';
console.log(str.replace(/(?:^|\s)\S/g, function (m0) { return m0.toUpperCase(); }));
Finally, here we're looking for (and uppercasing) all non-space characters that are preceded by the beginning of the string or a space character; i.e. we're uppercasing the start of each (space-separated) word.
All can be done by regex replace.
"lovisa t".replace(/(^|\s)\w/g, s=>s.toUpperCase());
Try this one (if it will be helpfull, better move constants to other place, due performance issues(yes, regexp creation is not fast)):
function normalize(str){
var LOW_DASH = /\_/g;
var NORMAL_TEXT_REGEXP = /([a-z])([A-Z])/g;
if(!str)str = '';
if(str.indexOf('_') > -1) {
str = str.replace(LOW_DASH, ' ');
}
if(str.match(NORMAL_TEXT_REGEXP)) {
str = str.replace(NORMAL_TEXT_REGEXP, '$1 $2');
}
if(str.indexOf(' ') > -1) {
var p = str.split(' ');
var out = '';
for (var i = 0; i < p.length; i++) {
if (!p[i])continue;
out += p[i].charAt(0).toUpperCase() + p[i].substring(1) + (i !== p.length - 1 ? ' ' : '');
}
return out;
} else {
return str.charAt(0).toUpperCase() + str.substring(1);
}
}
console.log(normalize('firstLast'));//First Last
console.log(normalize('first last'));//First Last
console.log(normalize('first_last'));//First Last
I’ve been trying to get a JavaScript regex command to turn something like "thisString" into "This String" but the closest I’ve gotten is replacing a letter, resulting in something like "Thi String" or "This tring". Any ideas?
To clarify I can handle the simplicity of capitalizing a letter, I’m just not as strong with RegEx, and splitting "somethingLikeThis" into "something Like This" is where I’m having trouble.
"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
displays
This String Is Good
(function() {
const textbox = document.querySelector('#textbox')
const result = document.querySelector('#result')
function split() {
result.innerText = textbox.value
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, (str) => str.toUpperCase())
};
textbox.addEventListener('input', split);
split();
}());
#result {
margin-top: 1em;
padding: .5em;
background: #eee;
white-space: pre;
}
<div>
Text to split
<input id="textbox" value="thisStringIsGood" />
</div>
<div id="result"></div>
I had an idle interest in this, particularly in handling sequences of capitals, such as in xmlHTTPRequest. The listed functions would produce "Xml H T T P Request" or "Xml HTTPRequest", mine produces "Xml HTTP Request".
function unCamelCase (str){
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
There's also a String.prototype version in a gist.
This can be concisely done with regex lookahead (live demo):
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).join(' ');
}
(I thought that the g (global) flag was necessary, but oddly enough, it isn't in this particular case.)
Using lookahead with split ensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).map(function(p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join(' ');
}
The map array method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a for loop.
I think this should be able to handle consecutive uppercase characters as well as simple camelCase.
For example: someVariable => someVariable, but ABCCode != A B C Code.
The below regex works on your example but also the common example of representing abbreviations in camcelCase.
"somethingLikeThis"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "something Like This"
"someVariableWithABCCode"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "some Variable With ABC Code"
You could also adjust as above to capitalize the first character.
Lodash handles this nicely with _.startCase()
function spacecamel(s){
return s.replace(/([a-z])([A-Z])/g, '$1 $2');
}
spacecamel('somethingLikeThis')
// returned value: something Like This
A solution that handles numbers as well:
function capSplit(str){
return str.replace(
/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g,
function(match, first){
if (first) match = match[0].toUpperCase() + match.substr(1);
return match + ' ';
}
)
}
Tested here [JSFiddle, no library. Not tried IE]; should be pretty stable.
Try this solution here -
var value = "myCamelCaseText";
var newStr = '';
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === value.charAt(i).toUpperCase()) {
newStr = newStr + ' ' + value.charAt(i)
} else {
(i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
}
}
return newStr;
If you don't care about older browsers (or don't mind using a fallback reduce function for them), this can split even strings like 'xmlHTTPRequest' (but certainly the likes of 'XMLHTTPRequest' cannot).
function splitCamelCase(str) {
return str.split(/(?=[A-Z])/)
.reduce(function(p, c, i) {
if (c.length === 1) {
if (i === 0) {
p.push(c);
} else {
var last = p.pop(), ending = last.slice(-1);
if (ending === ending.toLowerCase()) {
p.push(last);
p.push(c);
} else {
p.push(last + c);
}
}
} else {
p.push(c.charAt(0).toUpperCase() + c.slice(1));
}
return p;
}, [])
.join(' ');
}
My version
function camelToSpace (txt) {
return txt
.replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '$1 $2 $3$4')
.replace(/ +/g, ' ')
}
camelToSpace("camelToSpaceWithTLAStuff") //=> "camel To Space With TLA Stuff"
const value = 'camelCase';
const map = {};
let index = 0;
map[index] = [];
for (let i = 0; i < value.length; i++) {
if (i !== 0 && value[i] === value[i].toUpperCase()) {
index = i;
map[index] = [];
}
if (i === 0) {
map[index].push(value[i].toUpperCase());
} else {
map[index].push(value[i]);
}
}
let resultArray = [];
Object.keys(map).map(function (key, index) {
resultArray = [...resultArray, ' ', ...map[key]];
return resultArray;
});
console.log(resultArray.join(''));
Not regex, but useful to know plain and old techniques like this:
var origString = "thisString";
var newString = origString.charAt(0).toUpperCase() + origString.substring(1);