I have a string, var str = "Runner, The (1999)";
Using substr(), I need to see if ", The" is contained in str starting from 7 characters back, then if it is, remove those characters and put them in the start. Something like this:
if (str.substr(-7) === ', The') // If str has ', The' starting from 7 characters back...
{
str = 'The ' + str.substr(-7, 5); // Add 'The ' to the start of str and remove it from middle.
}
The resulting str should equal "The Runner (1999)"
Please, no regular expressions or other functions. I'm trying to learn how to use substr.
Here you go, using only substr as requested:
var str = "Runner, The (1999)";
if(str.substr(-12, 5) === ', The') {
str = 'The ' + str.substr(0, str.length - 12) + str.substr(-7);
}
alert(str);
Working JSFiddle
It should be noted that this is not the best way to achieve what you want (especially using hardcoded values like -7 – almost never as good as using things like lastIndexOf, regex, etc). But you wanted substr, so there it is.
var str = "Runner, The (1999)";
if(str.indexOf(", The") != -1) {
str = "The "+str.replace(", The","");
}
If you want to use just substr:
var a = "Runner, The (1999)"
var newStr;
if (str.substr(-7) === ', The')
newStr= 'The ' +a.substr(0,a.length-a.indexOf('The')-4) + a.substr(a.indexOf('The')+3)
Use a.substr(0,a.length-a.indexOf('The')-4) to obtain the words before "The" and a.substr(a.indexOf('The')+3) to obtain the words after it.
So, you say that the solution should be limited to only substr method.
There will be different solutions depending on what you mean by:
", The" is contained in str starting from 7 characters back
If you mean that it's found exactly in -7 position, then the code could look like this (I replaced -7 with -12, so that the code returned true):
function one() {
var a = "Runner, The (1999)";
var b = ", The";
var c = a.substr(-12, b.length);
if (c == b) {
a = "The " + a.substr(0, a.length - 12) +
a.substr(a.length - 12 + b.length);
}
}
If, however, substring ", The" can be found anywhere between position -7 and the end of the string, and you really need to use only substr, then check this out:
function two() {
var a = "Runner, The (1999)";
var b = ", The";
for (var i = a.length - 12; i < a.length - b.length; i++) {
if (a.substr(i, b.length) == b) {
a = "The " + a.substr(0, i) + a.substr(i + b.length);
break;
}
}
}
Related
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);
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
So I technically already solved this issue, but I was hoping for a better solution using some funky regex.
The issue is:
We got strings this:
2+{2+(2)},
10+(20+2)+2
The goal is to match the 'plus' signs that are not in any sort of bracket.
i.e. in the previous strings it should match
2 + {2+(2)} ,
10 + (20+2) + 2
at the moment what I am doing is matching all plus signs, and then checking to see if the sign has any bracket in front of it (using regex), if it does then get rid of it.
I was hoping for a neater regex solution, is that possible?
To reiterate, I need the location of the strings, at the moment I am using javascript to do this, so ideally a js solution is preferred, but the pattern is really what I am looking for.
You could perhaps just replace everything inside () or {} with spaces:
'10 + (20+2) + 2'.replace(/\([^)]*?\)|\{[^}]*?\}/g, m => ' '.repeat(m.length));
This would result in
10 + + 2
Meaning the position of the strings aren't changed.
Note: It won't work well with nested things of the same type, ex (1 + (1 + 1) + 1), but it works with (1 + { 1 + 1 } + 1).
Bigger solution, using the same logic, but that works with nested stuff
var input = '10 + { 1 + (20 + (1 + { 3 + 3 } + 1) + 2) + 2 }';
var result = [];
var opens = 0;
for (var i = 0; i < input.length; ++i) {
var ch = input[i];
if (/\(|\{/.test(ch)) {
opens++;
result[i] = ' ';
}
else if (/\)|\}/.test(ch)) {
opens--;
result[i] = ' ';
}
else {
if (!opens) result[i] = input[i];
else result[i] = ' ';
}
}
result = result.join('');
// "10 + "
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
Hi I'm going to make a calculator and I want a +/- button. I want to get the latest *, -, +, / in the string and define whats the laststring.
For example:
str="2+3*13"
I want this to be split into:
strA="2+3*"
strB="13"
Another example:
str="3-2+8"
Should split into:
strA="3-2+"
strB="8"
Use lastIndexOf and one of the substring methods:
var strA, strB,
// a generic solution for more operators might be useful
index = Math.max(str.lastIndexOf("+"), str.lastIndexOf("-"), str.lastIndexOf("*"), str.lastIndexOf("/"));
if (index < 0) {
strA = "";
strB = str;
} else {
strA = str.substr(0, index+1);
strB = str.substr(index+1);
}
You can use replace, match, and Regular Expressions:
str="3-2+8"
strA = str.replace(/\d+$/, "")
strB = str.match(/\d+$/)[0]
console.log(str, strA, strB);
> 3-2+8 3-2+ 8
You can use regular expression and split method:
var parts = "2 + 4 + 12".split(/\b(?=\d+\s*$)/);
Will give you and array:
["2 + 4 + ", "12"]
Couple of tests:
"(2+4)*230" -> ["(2+4)*", "230"]
"(1232-74) / 123 " -> ["(1232-74) / ", "123 "]
"12 * 32" -> ["12 * ", "32"]