JavaScript - How can I get the last different index in string but - javascript

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"]

Related

Javascript - Regex to replace last 4 digit

I have a number variable at JavaScript and i want it replaced in last 4 character. Example:
I have a number 123456789 and i want it to be replaced like this 12345****
Is there any regex to do that in JavaScript?
Use replace() with regex /\d{4}$/
var res = '123456789'.replace(/\d{4}$/, '****');
document.write(res);
Regex explanation
Or using substring() or substr()
var str = '123456789',
res = str.substr(0, str.length - 4) + '****';
document.write(res);
You could use substring as well:
var s = '123456789';
var ns = s.substring(0, s.length - 4) + '****';
document.write(ns);

JavaScript substr(), Get Characters in the Middle of the String

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

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 get total number of words in a string in javascript [duplicate]

This question already has answers here:
Regular Expression for accurate word-count using JavaScript
(8 answers)
Closed 8 years ago.
I was trying to count the total number of words in a sentence. I have used the following code in Javascript.
function countWords(){
s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
alert(s.split(' ').length);
}
So if I gave following inputs,
"Hello world" -> alerts 2 //fine
"Hello world<space>" -> alerts 3 // supposed to alert 2
"Hello world world" -> alerts 3 //fine
Where I went wrong?
here you will find all you need.
http://jsfiddle.net/deepumohanp/jZeKu/
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
try this one please:
var word = "str";
function countWords(word) {
var s = word.length;
if (s == "") {
alert('count is 0')
}
else {
s = s.replace (/\r\n?|\n/g, ' ')
.replace (/ {2,}/g, ' ')
.replace (/^ /, '')
.replace (/ $/, '');
var q = s.split (' ');
alert ('total count is: ' + q.length);
}
}
Split will split event if there is your separator (in your case ' ') at the end of the string, resulting in creating a last [] item in the list.
What you can do is use the split(" ") function (including the space inside quotation) to convert the string to an array consisting of only the words. Then you can get the length of the array by using array.length which would essentially be the number of words in your string.

Parse complex string with one regular expression

How can I get from this string
genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990
this
genre: [Drama, Comedy],
cast: [Leonardo DiCaprio, Cmelo Hotentot],
year: [1986-1990]
with one regular expression?
This could be done using one regex and overload of replace function with replacer as a second argument. But honestly, I have to use one more replace to get rid of pluses (+) - I replaced them by a space () char:
var str = 'genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990';
str = str.replace(/\+/g, ' ');
var result = str.replace(/(\w+:)(\s?)([\w,\s-]+?)(\s?)(?=\w+:|$)/g, function (m, m1, m2, m3, m4, o) {
return m1 + ' [' + m3.split(',').join(', ') + ']' + (o + m.length != str.length ? ',' : '') + '\n';
});
You could find the full example on jsfiddle.
You will not get them into arrays from the start, but it can be parsed if the order stays the same all the time.
var str = "genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990";
str = str.replace(/\+/g," ");
//Get first groupings
var re = /genre:\s?(.+)\scast:\s?(.+)\syear:\s(.+)/
var parts = str.match(re)
//split to get them into an array
var genre = parts[1].split(",");
var cast = parts[2].split(",");
var years = parts[3];
console.log(genre);
You can't do this using only regular expressions cause you're trying to parse a (tiny) grammar.

Categories