How to get the last value of a string? - javascript

How can i control in java script, wheter the last character in a string is a ", " and how can i delete the last character, if it is a ", "?
var stringToControl = "ABC, XYZ, OOP, "

"Comma followed by any number of white space characters at the end of a string" can be expressed as a regular expression: /,\s*$/.
So to get rid of it you can replace it with an empty string:
stringToControl = stringToControl.replace(/,\s*$/,'');

Try this:
if (stringToControl.slice(-2) === ', ') {
stringToControl = stringToControl.slice(0, -2);
}
slice method returns part of a string. First argument is the start position and optional second argument - the end position. If you don't pass second arguments, slice will return part from start argument to the end of the string. If you pass negative value, it means the position from the end (so .slice(-2) means 2 last characters).
Here is an article on MDN
Another approach is to use RegExp:
stringToControl = stringToControl.replace(/, $/, '');

use slice
var temp = "abcd,aa,a,as,c,d, ".trim();
if(temp.endsWith(','))
temp = temp.slice(0,-1);
temp

Related

capture the string next to known string using javascript/jQuery

I have a long string. How can I find a string next to the known string.
example: '.lot of text..."number":"999.999.9999","make_model":"device name"....lot of text.'.
I know this value "999.999.9999". Using this as a sub string how do I capture "device name" and pass it as an alert/console.log? The device name is not a constant length.
Thanks
you can do something like this if you are sure the number is only repeated once and length is always the same and make_model is always next to it.
basically it finds index of number and adds the length of number plus make_model ("999.999.9999","make_model":") which is 29 characters. and then we get the rest of string after this until we reach a double quotation and thats the end of make_model and what you want.
var str = '.lot of text..."number":"999.999.9999","make_model":"device name"....lot of text.';
var chop = str.substr(str.indexOf('"999.999.9999"') + 29);
chop = chop.substring(0,chop.indexOf('"'));
console.log(chop);
A very straight forward answer is using JSON.parse()
/* surround string with braces { <your string> } */
var input_str = '{' + '"foo":"bar","number":"999.999.9999","make_model":"some model name","device name":"some dummy device","name":"Arvind","profile":"freelancer"' + '}';
var json = JSON.parse(input_str);
console.log(json['device name']);

single regex to capitalize first letter and replace dot

Trying out with a regex for simple problem. My input string is
firstname.ab
And am trying to output it as,
Firstname AB
So the main aim is to capitalize the first letter of the string and replace the dot with space. So chose to write two regex to solve.
First One : To replace dot with space /\./g
Second One : To capitalize the first letter /\b\w/g
And my question is, Can we do both operation with a single regex ?
Thanks in advance !!
You can use a callback function inside the replace:
var str = 'firstname.ab';
var result = str.replace(/^([a-zA-Z])(.*)\.([^.]+)$/, function (match, grp1, grp2, grp3, offset, s) {
return grp1.toUpperCase() + grp2 + " " + grp3.toUpperCase();
});
alert(result);
The grp1, grp2 and grp3 represent the capturing groups in the callback function. grp1 is a leading letter ([a-zA-Z]). Then we capturing any number of character other than newline ((.*) - if you have linebreaks, use [\s\S]*). And then comes the literal dot \. that we do not capture since we want to replace it with a space. And lastly, the ([^.]+$) regex will match and the capture all the remaining substring containing 1 or more characters other then a literal dot till the end.
We can use capturing groups to re-build the input string this way.
var $input = $('#input'),
value = $input.val(),
value = value.split( '.' );
value[0] = value[0].charAt( 0 ).toUpperCase() + value[0].substr(1),
value[1] = value[1].toUpperCase(),
value = value.join( ' ' );
$input.val( value );
It would be much easier if you simply split the value, process the string in the array, and join them back.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="first.ab" id="input">

What's the exact regex to match the proper string?

My string has [1212,1212],[1212,11212],...
I'd like to extract each value into an array for example I'd want 1212,1212 as one pair and evaluate a series of steps.
Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. Basically I'm a noob in Regex, could someone please help.
Thanks in advance
You need some modifications for your regular expression for it to work correctly:
/\[[0-9]+,[0-9]+\]/g
You need to escape square brackets [ because they have special meaning.
[0-9] matches only one digits, you need the + quantifier to match one or more digits and thus [0-9]+.
Use the global modifier g to extract all matches.
Then you can extract all the values into an array like this:
var input = "[1212,1212],[1212,11212]";
var pattern = /\[[0-9]+,[0-9]+\]/g;
var result = [];
var currentMatch;
while((currentMatch = pattern.exec(input)) != null) {
result.push(currentMatch.toString());
}
result;
Or if you don't need to find the matches successively one at a time, then you can use String.match() as #Matthew Mcveigh did:
var input = "[1212,1212],[1212,11212]";
var result = input.match(/\[[0-9]+,[0-9]+\]/g);
It seems like you just need to match one or more digits before and after a comma, so you could do the following:
"[1212,1212],[1212,11212]".match(/\d+,\d+/g)
Which will give you the array: ["1212,1212", "1212,11212"]
To extract the pairs:
var result = "[1212,1212],[1212,11212]".match(/\d+,\d+/g);
for (var i = 0; i < result.length; i++) {
var pair = result[i].match(/\d+/g),
left = pair[0], right = pair[1];
alert("left: " + left + ", right: " + right);
}
You need to escape the literal brackets that you want to match. You can also use \d to match "any digit", which makes it tidier. Also, you're only matching one digit. You need to match "one or more" (+ quantifier)
/\[\d+,\d+\]/g
That g modifier finds all matches in the string, otherwise only the first one is found.

How can I obtain substrings from a string in javascript?

I have a string that looks like this:
var stringOriginal = "72157632110713449SomeDynamicText";
I want to separate this string into two substrings:
One substring is the first 17 digits
One substring is the rest of the string
I want these stored in two separate variables, like this:
var string1 = "72157632110713449"; //First static 17 digits
var string2 = "SomeDynamicText"; // Dynamic Text
Assuming your string is fixed, you can use the substring or substr string functions. The two are very similar:
substr(start, length) obtains a value from the start index to a specified length (or to the end, if unspecified)
substring(start, end) obtains a value from the start index to the end index (or the end, if unspecified)
So, one way you could do it by mixing and matching the two, is like this:
var string1 = stringOriginal.substring(0, 17);
# interestingly enough, this does the same in this case
var string1 = stringOriginal.substr(0, 17);
var string2 = stringOriginal.substr(17);
If, however, you need a more sophisticated solution (e.g. not a fixed length of digits), you could try using a regex:
var regex = /(\d+)(\w+)/;
var match = regex.exec(stringOriginal);
var string1 = match[1]; // Obtains match from first capture group
var string2 = match[2]; // Obtains match from second capture group
Of course, this adds to the complexity, but is more flexible.
Here you go:
string1 = stringOriginal.substring(0, 17);
string2 = stringOriginal.substring(17, stringOriginal.length);
or
string2 = stringOriginal.substring(17);
//Second parameter is optional. The index where to stop the extraction.
//If second parameter is omitted, it extracts the rest of the string
This will split the string into vars given that the first 17 characters always go into string1 and the remainder into string2.
var string1 = stringOriginal.substring(0,17);
var string2 = stringOriginal.substring(17,stringOriginal.length);
Assuming that you want to split the string by separating initial digits from the rest regardless of length :
string = string.match (/^(\d+)(.*)/) || [string, '', ''];
string[1] will hold the initial digits, string[2] the rest of the string, the original string will be in string[0].
If string does not start with a digit, string[0] will hold the original string and string[1] and string[2] will be empty strings.
By changing the code to :
string = string.match (/^(\d*)(.*)/);
strings containing no initial digits will have string[1] empty and string[2] will have the same value as string[0], i.e the initial string. In this case there is no need to handle the case of a failing match.

cut out part of a string

Say, I have a string
"hello is it me you're looking for"
I want to cut part of this string out and return the new string, something like
s = string.cut(0,3);
s would now be equal to:
"lo is it me you're looking for"
EDIT: It may not be from 0 to 3. It could be from 5 to 7.
s = string.cut(5,7);
would return
"hellos it me you're looking for"
You're almost there. What you want is:
http://www.w3schools.com/jsref/jsref_substr.asp
So, in your example:
Var string = "hello is it me you're looking for";
s = string.substr(3);
As only providing a start (the first arg) takes from that index to the end of the string.
Update, how about something like:
function cut(str, cutStart, cutEnd){
return str.substr(0,cutStart) + str.substr(cutEnd+1);
}
Use
substring
function
Returns a subset of a string between
one index and another, or through the
end of the string.
substring(indexA, [indexB]);
indexA
An integer between 0 and one less than the length of the string.
indexB
(optional) An integer between 0 and the length of the string.
substring extracts characters from indexA up to but not including indexB. In particular:
* If indexA equals indexB, substring returns an empty string.
* If indexB is omitted, substring extracts characters to the end
of the string.
* If either argument is less than 0 or is NaN, it is treated as if
it were 0.
* If either argument is greater than stringName.length, it is treated as
if it were stringName.length.
If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).
Some other more modern alternatives are:
Split and join
function cutFromString(oldStr, fullStr) {
return fullStr.split(oldStr).join('');
}
cutFromString('there ', 'Hello there world!'); // "Hello world!"
Adapted from MDN example
String.replace(), which uses regex. This means it can be more flexible with case sensitivity.
function cutFromString(oldStrRegex, fullStr) {
return fullStr.replace(oldStrRegex, '');
}
cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
s = string.cut(5,7);
I'd prefer to do it as a separate function, but if you really want to be able to call it directly on a String from the prototype:
String.prototype.cut= function(i0, i1) {
return this.substring(0, i0)+this.substring(i1);
}
string.substring() is what you want.
Just as a reference for anyone looking for similar function, I have a String.prototype.bisect implementation that splits a string 3-ways using a regex/string delimiter and returns the before,delimiter-match and after parts of the string....
/*
Splits a string 3-ways along delimiter.
Delimiter can be a regex or a string.
Returns an array with [before,delimiter,after]
*/
String.prototype.bisect = function( delimiter){
var i,m,l=1;
if(typeof delimiter == 'string') i = this.indexOf(delimiter);
if(delimiter.exec){
m = this.match(delimiter);
i = m.index;
l = m[0].length
}
if(!i) i = this.length/2;
var res=[],temp;
if(temp = this.substring(0,i)) res.push(temp);
if(temp = this.substr(i,l)) res.push(temp);
if(temp = this.substring(i+l)) res.push(temp);
if(res.length == 3) return res;
return null;
};
/* though one could achieve similar and more optimal results for above with: */
"my string to split and get the before after splitting on and once".split(/and(.+)/,2)
// outputs => ["my string to split ", " get the before after splitting on and once"]
As stated here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split
If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.
You need to do something like the following:
var s = "I am a string";
var sSubstring = s.substring(2); // sSubstring now equals "am a string".
You have two options about how to go about it:
http://www.quirksmode.org/js/strings.html#substring
http://www.quirksmode.org/js/strings.html#substr
Try the following:
var str="hello is it me you're looking for";
document.write(str.substring(3)+"<br />");
You can check this link
this works well
function stringCutter(str,cutCount,caretPos){
let firstPart = str.substring(0,caretPos-cutCount);
let secondPart = str.substring(caretPos,str.length);
return firstPart + secondPart;
}

Categories

Resources