Replace underscore with brackets using javascript - javascript

I have a string AverageLogon_Seconds_
I need to replace the first underscore with '(' and second Underscore with ')'.
Means I need to get the text like AverageLogon(Seconds).
I have checked with str.replace(/_/g, ')'); , but it will replace both the underscore iwth ')'.
Can anyone help me on this.
Thanks

Do it with String#replace with a callback and a counter variable. Replace _ with ( in an odd position and ) in an even position where the counter variable can be used for finding out the position.
var str = 'AverageLogon_Seconds_',
i = 0;
var res = str.replace(/_/g, function() {
return i++ % 2 == 0 ? '(' : ')';
});
console.log(res);

I feel like it would be more prudent to target the "_something_" pattern as a whole. Something like
str.replace(/_([a-z0-9 -]+)_/gi, '($1)')
You can narrow that [a-z0-9 -] character class down based on the characters you expect to appear between the underscores. For now, I've got letters, numbers, spaces and hyphens.
var tests = [
'AverageLogon_Seconds_',
'AverageLogon_Seconds_ and some other_data_',
'Oh no, too_many_underscores___'],
out = document.getElementById('out'),
rx = /_([a-z0-9 -]+)_/gi;
tests.forEach(function(test) {
out.innerHTML += test + ' => ' + test.replace(rx, '($1)') + '\n';
});
<pre id="out"></pre>

Thats easy. Just a one liner needed.
testString = "AverageLogon_Seconds_";
replacedString = testString.replace(/_/, '(').replace(/_/, ')');
console.log(replacedString);
Output : "AverageLogon(Seconds)"

var str = 'AverageLogon_Seconds_', replacement = ')';
//replace the last occurence of '_' with ')'
str = str.replace(/_([^_]*)$/,replacement+'$1');
//replace the remaining '_' with '('
console.log(str);

Pranav's solution is nice. I tend to like to write things that I can very quickly reason about (i.e. sometimes less elegant). Another way (read in DJ Khaled's voice):
function replaceUnderscores(str) {
return str.split('_').map(function (part, ind) {
if (part === '') {
return '';
}
if (ind % 2 === 0) {
return part + '(';
} else {
return part + ')';
}
}).join('');
}
// "AverageLogon(Seconds)"
console.log(replaceUnderscores('AverageLogon_Seconds_'));

will this work
var t = "AverageLogon_Seconds_";
var ctr=0;
while(t.contains('_')){
if(ctr==0){
t= t.replace('_','(');
ctr++;
}
else{
t= t.replace('_',')');
ctr--;
}
}

Related

Javascript replace every 6th colon in array

I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.
arrayProducts[i] = arrayProducts[i].join(':');
When i use console.log(arrayProducts); this is my result:
F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3
This is what I want:
F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3
Thanks for reading!
Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.
You can just count the number of colon occurences and replace every nth of them.
var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3', counter = 0;
res = str.replace(/:/g, function(v) {
counter++;
return !(counter % 7) ? ',' : v;
});
console.log(res);
A regex solution is viable. You can use a function as the second parameter of the .replace method to make full use of backreferences.
var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3';
str = str.replace(/((?:[^:]*:){6}(?:[^:]*)):/g, function() {
var matches = arguments;
return matches[1] + ',';
});
console.log(str);
What you are looking for is to split over the following expression :[A-Z]
(assuming that your rows always start with this range)
a simple solution could be:
mystring.split(/:[A-Z]/).join(',')
/:[A-Z]/ matches any : followed by a uppercase letter
You could use replace with a look for six parts with colon and replace the seventh.
var string = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3',
result = string.replace(/(([^:]*:){6}[^:]*):/g, '$1,');
console.log(result);
Another solution (based on the number of iteration)
using map method:
str.split(':').map((v, i) => (i % 7 === 0 ? ',' : ':') + v ).join('').slice(1)
using reduce method:
str.split(':').reduce((acc,v, i) => {
return acc + (i % 7 === 0 ? ',' : ':' ) + v ;
}, '').slice(1)
Note: arrow expression does not work on old browsers
maybe you can try this approach,
loop your array and join it manually, something like :
var strarr = "F200:0:00000:1:100:0:1:KPO2:0:00000:1:200:0:2:HGB1:0:00000:1:300:0:3";
var arr = strarr.split(":")
var resStr = "";
for(var i = 0; i < arr.length; i++)
{
if(i > 0 && i%7 == 0)
resStr = resStr + "," + arr[i]
else
resStr = resStr + ( resStr == "" ? "" : ":") + arr[i];
}
console.log(resStr);

How to replace a character with an specific indexOf to uppercase in a string?

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

JavaScript split and join

I have a string, 15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt, I'd like to make it looks like 15.Prototypal...-Slider.txt
The length of the text is 56, how can I keep the first 12 letters and 10 last letters (incuding punctuation marks) and replace the others to ...
I don't really know how to commence the code, I made something like
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
str.split("// ",1);
although this gives me what I need, how do I have the results base on letters not words.
You can use str.slice().
function middleEllipsis(str, a, b) {
if (str.length > a + b)
return str.slice(0, a) + '...' + str.slice(-b);
else
return str;
}
middleEllipsis("15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt", 12, 10);
// "15.Prototypa...Slider.txt"
middleEllipsis("mpchc64.mov", 12, 10);
// "mpchc64.mov"
This function will do what you ask for:
function fixString(str) {
var LEN_PREFIX = 12;
var LEN_SUFFIX = 10;
if (str.length < LEN_PREFIX + LEN_SUFFIX) { return str; }
return str.substr(0, LEN_PREFIX) + '...' + str.substr(str.length - LEN_SUFFIX - 1);
}
You can adjust the LEN_PREFIX and LEN_SUFFIX as needed, but I've the values you specified in your post. You could also make the function more generic by making the prefix and suffix length input arguments to your function:
function fixString(str, prefixLength, suffixLength) {
if (str.length < prefixLength + suffixLength) { return str; }
return str.substr(0, prefixLength) + '...' + str.substr(str.length - suffixLength - 1);
}
I'd like to make it looks like 15.Prototypal...-Slider.txt
LIVE DEMO
No matter how long are the suffixed and prefixed texts, this will get the desired:
var str = "15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt",
sp = str.split('-'),
newStr = str;
if(sp.length>1) newStr = sp[0]+'...-'+ sp.pop() ;
alert( newStr ); //15.Prototypal...-Slider.txt
Splitting the string at - and using .pop() method to retrieve the last Array value from the splitted String.
Instead of splitting the string at some defined positions it'll also handle strings like:
11.jQuery-infinite-loop-a-Gallery.txt returning: 11.jQuery...-Gallery.txt
Here's another option. Note that this keeps the first 13 characters and last 11 because that's what you gave in your example.:
var shortenedStr = str.substr(0, 13) + '...' + str.substring(str.length - 11);
You could use the javascript substring command to find out what you want.
If you string is always 56 characters you could do something like this:
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
var newstr = str.substring(0,11) + "..." + str.substring(45,55)
if your string varies in length I would highly recommend finding the length of the string first, and then doing the substring.
have a look at: http://www.w3schools.com/jsref/jsref_substring.asp

How to trim specific characters from the end of the JavaScript string?

In JavaScript, how do I trim from the right(string end)?
I have the following example:
var s1 = "this is a test~";
var s = s1.rtrim('~');
Use a RegExp. Don't forget to escape special characters.
s1 = s1.replace(/~+$/, ''); //$ marks the end of a string
// ~+$ means: all ~ characters at the end of a string
You can modify the String prototype if you like. Modifying the String prototype is generally frowned upon, but I personally prefer this method, as it makes the code cleaner IMHO.
String.prototype.rtrim = function(s) {
return this.replace(new RegExp(s + "*$"),'');
};
Then call...
var s1 = "this is a test~";
var s = s1.rtrim('~');
alert(s);
IMO this is the best way to do a right/left trim and therefore, having a full functionality for trimming (since javascript supports string.trim natively)
String.prototype.rtrim = function (s) {
if (s == undefined)
s = '\\s';
return this.replace(new RegExp("[" + s + "]*$"), '');
};
String.prototype.ltrim = function (s) {
if (s == undefined)
s = '\\s';
return this.replace(new RegExp("^[" + s + "]*"), '');
};
Usage example:
var str1 = ' jav '
var r1 = mystring.trim(); // result = 'jav'
var r2 = mystring.rtrim(); // result = ' jav'
var r3 = mystring.rtrim(' v'); // result = ' ja'
var r4 = mystring.ltrim(); // result = 'jav '
There are no trim, ltrim, or rtrim functions in Javascript. Many libraries provide them, but generally they will look something like:
str.replace(/~*$/, '');
For right trims, the following is generally faster than a regex because of how regex deals with end characters in most browsers:
function rtrim(str, ch)
{
let i = str.length;
while (i-- && str.charAt(i) === ch);
return str.substring(0, i + 1);
}
console.log(rtrim("moo", "x"));
console.log(rtrim("moo", "o"));
console.log(rtrim("oo", "o"));
A solution using a regular expression:
"hi there~".replace(/~*$/, "")
str.trimEnd();
str.trimRight();
These are currently stage 4 proposals expected to be part of ES2019. They work in NodeJS and several browsers.
See below for more info:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd
This removes a specified string or character from the right side of a string
function rightTrim(sourceString,searchString)
{
for(;;)
{
var pos = sourceString.lastIndexOf(searchString);
if(pos === sourceString.length -1)
{
var result = sourceString.slice(0,pos);
sourceString = result;
}
else
{
break;
}
}
return sourceString;
}
Please use like so:
rightTrim('sourcecodes.....','.'); //outputs 'sourcecodes'
rightTrim('aaabakadabraaa','a'); //outputs 'aaabakadabr'
My 2 cents:
function rtrim(str: string, ch: string): string
{
var i:number = str.length - 1;
while (ch === str.charAt(i) && i >= 0) i--
return str.substring(0, i + 1);
}
const tests = ["/toto/", "/toto///l/", "/toto////", "/////", "/"]
tests.forEach(test => {
console.log(`${test} = ${rtrim(test, "/")}`)
})
Gives
"/toto/ = /toto"
"/toto///l/ = /toto///l"
"/toto//// = /toto"
"///// = "
"/ = "
You can add lodash library. It is a JavaScript utility library, There are some trim functions. You can use:
_.trimEnd('this is a test~', '~')
This is old, I know. But I don't see what's wrong with substr...?
function rtrim(str, length) {
return str.substr(0, str.length - length);
}

How to convert "camelCase" to "Camel Case"?

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

Categories