Counting characters between 2 specified words in a string - javascript

This is my text string:
0000> hello world <0000
I want to count the characters between "0000>" and "<0000".

This will work:
s = "0000> hello my name is james, whats yours? <0000";
s.match(/0000>(.*?)<0000/)[1].length // returns 38;
But then again, so will this :-)
s.length - 10; // returns 38

This will do:
function count(string) {
var match = /0000>(.*)<0000/g.exec(string);
if (match.length > 1) {
return match[1].trim().length;
} else {
return null;
}
}
alert (count("0000> hello my name is james, whats yours? <0000"));
And the jsfiddle demo: http://jsfiddle.net/pSJGk/1/

Well, something like this would count everything (including spaces) between 0000> and <0000:
'0000> hello my name is james, whats yours? <0000'
.split(/0000>|<0000/g)[1].length; //=> 38
Or
'0000> hello my name is james, whats yours? <0000'
.replace(/0000>|<0000/g,'').length; //=> 38

function getLengthBetween(str,startStr,stopStr) {
var startPos = str.indexOf(startStr);
if(startPos == -1) {
return 0;
}
var startOffset = startPos+startStr.length;
var stopPos = str.indexOf(stopStr,startOffset);
if(stopPos == -1) {
stopPos = str.length;
}
return stopPos-startOffset;
}
Usage:
getLengthBetween("0000> hello my name is james, whats yours? <0000","0000>","<0000");

I'd suggest:
var str = " 0000> hello my name is james, whats yours? <0000",
start = "0000>",
end = "<0000",
between = str.substring(str.indexOf(start) + start.length, str.indexOf(end)).length;
console.log(between);​
JS Fiddle demo.
This doesn't, however, trim the white-space from after the first match, or from before the second. This could be altered, of course, to match any given string delimiters by simply changing the variables.
References:
indexOf().
length.
substring().

Related

Javascript: Returning the last word in a string

right to it:
I have a words string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?
function test(words) {
var n = words.indexOf(" ");
var res = words.substring(n+1,-1);
return res;
}
I've been told to use indexOf and substring but it's not required. Anyone have an easy way to do this? (with or without indexOf and substring)
Try this:
you can use words with n word length.
example:
words = "Hello World";
words = "One Hello World";
words = "Two Hello World";
words = "Three Hello World";
All will return same value: "World"
function test(words) {
var n = words.split(" ");
return n[n.length - 1];
}
You could also:
words.split(" ").pop();
Just chaining the result (array) of the split function and popping the last element would do the trick in just one line :)
var data = "Welcome to Stack Overflow";
console.log(data.split(" ").splice(-1));
Output
[ 'Overflow' ]
This works even if there is no space in the original string, so you can straight away get the element like this
var data = "WelcometoStackOverflow";
console.log(data.split(" ").splice(-1)[0]);
Output
WelcometoStackOverflow
You want the last word, which suggests lastIndexOf may be more efficient for you than indexOf. Further, slice is also a method available to Strings.
var str = 'foo bar fizz buzz';
str.slice(
str.lastIndexOf(' ') + 1
); // "buzz"
See this jsperf from 2011 showing the split vs indexOf + slice vs indexOf + substring and this perf which shows lastIndexOf is about the same efficiency as indexOf, it mostly depends on how long until the match happens.
To complete Jyoti Prakash, you could add multiple separators (\s|,) to split your string (via this post)
Example:
function lastWord(words) {
var n = words.split(/[\s,]+/) ;
return n[n.length - 1];
}
Note: regex \s means whitespace characters : A space character, A tab character, A carriage return character, A new line character, A vertical tab character, A form feed character
snippet
var wordsA = "Hello Worlda"; // tab
var wordsB = "One Hello\nWorldb";
var wordsC = "Two,Hello,Worldc";
var wordsD = "Three Hello Worldd";
function lastWord(words) {
var n = words.split(/[\s,]+/);
return n[n.length - 1];
}
$('#A').html( lastWord(wordsA) );
$('#B').html( lastWord(wordsB) );
$('#C').html( lastWord(wordsC) );
$('#D').html( lastWord(wordsD) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A:<span id="A"></span><br/>
B:<span id="B"></span><br/>
C:<span id="C"></span><br/>
D:<span id="D"></span><br/>
Adding from the accepted answer, if the input string is "Hello World " (note the extra space at the end), it will return ''. The code below should anticipate in case user fat-fingered " ":
var lastWord= function(str) {
if (str.trim() === ""){
return 0;
} else {
var splitStr = str.split(' ');
splitStr = splitStr.filter(lengthFilter);
return splitStr[splitStr.length - 1];
}
};
var lengthFilter = function(str){
return str.length >= 1;
};
Easiest way is to use slice method:-
For example:-
let words = "hello world";
let res = words.slice(6,13);
console.log(res);
/**
* Get last word from a text
* #param {!string} text
* #return {!string}
*/
function getLastWord(text) {
return text
.split(new RegExp("[" + RegExp.quote(wordDelimiters + sentenceDelimiters) + "]+"))
.filter(x => !!x)
.slice(-1)
.join(" ");
}
According to me the easiest way is:
lastName.trim().split(" ").slice(-1)
It will give the last word in a phrase, even if there are trailing spaces.
I used it to show the last name initials. I hope it works for you too.
Use split()
function lastword(words){
array = words.split(' ');
return array[1]
}
Its pretty straight forward.
You have got two words separated by space.
Lets break the string into array using split() method.
Now your array has two elements with indices 0 and 1.
Alert the element with index 1.
var str="abc def";
var arr=str.split(" ");
alert(arr[1]);

Javascript string functions?

I have strings like this:
abcdefg
abcde
abc
jjjj
I need is them trucated to show like this if more than a specified lenght:
abc ..
abc ..
abc
jjj ..
Is there any simple javascript code I can use for this functionality
The length property will tell you how many characters you have, and the substr method will let you extract the first three (if there are more than you want), you can then concatenate " .." with the + operator (although "…" would be the usual choice).
function truncate(str, len) {
if(str.length > len) {
return str.substring(0, len) + ' ..';
} else {
return str;
}
}
Well, without knowing if you have access to Array.each and some of the more recent additions:
// if you have them all in an array, loop through the array/
for( var i = 0; i < strs.length; i++ )
// substr( ind, len ) = return a substring
// beginning at index ind and of len length
strs[ i ] = strs[ i ].substr( 0, 3 );
Now, if you don't have them all in an array, then things become a good deal harder. How are you currently storing them?
I think the substring function would be helpful. If you can get the length of a string, use substring to truncate and concatenate ".." as necessary, this is easy. You could make it a function and encapsulate everything. Would you like help with the code?
All string will have a length property you can use to check length, but I would just pull a substring:
var str = 'abcdefg';
var shortened = str.substr(0,3);
see http://www.electrictoolbox.com/javascript-substr/ for details
else a simple code will do
var mystring = "aaaaaaaaaa";
var max_length = 3; //max length
mystring = mystring.substr(0, max_length);
mystring = mystring + '..'

Check if text is in a string

I want to check is some text is in a string for instance i have a string
str = "car, bycicle, bus"
and I have another string
str2 = "car"
I want to check if str2 is in str.
I am a newbie in javascript so please bear with me :)
Regards
if(str.indexOf(str2) >= 0) {
...
}
Or if you want to go the regex route:
if(new RegExp(str2).test(str)) {
...
}
However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.
ES5
if(str.indexOf(str2) >= 0) {
...
}
ES6
if (str.includes(str2)) {
}
str.lastIndexOf(str2) >= 0; this should work. untested though.
let str = "car, bycicle, bus";
let str2 = "car";
console.log(str.lastIndexOf(str2) >= 0);
Please use this :
var s = "foo";
alert(s.indexOf("oo") > -1);
Use the builtin .includes() string method to check for the existence of sub-string.
It return boolean which indicates if the sub-string included or not.
const string = "hello world";
const subString = "world";
console.log(string.includes(subString));
if(string.includes(subString)){
// SOME CODE
}
You can use this:
'a nice string'.includes('nice')
If you just want to check substring in a string you can use indexOf but if you want to check if the word is in the string or not, the other answers might not work correctly for example:
str = "carpet, bycicle, bus"
str2 = "car"
What you want car word is found not car in carpet
if(str.indexOf(str2) >= 0) {
// Still true here
}
// OR
if(new RegExp(str2).test(str)) {
// Still true here
}
So you can improve the regex a bit to make it work
str = "carpet, bycicle, bus"
str1 = "car, bycicle, bus"
stringCheck = "car"
// This will false
if(new RegExp(`\b${stringCheck}\b`).test(str)) {
}
// This will true
if(new RegExp(`\b${stringCheck}\b`,"g").test(str1)) {
}

Regular expression [Any number]

I need to test for "[any number]" in a string in javascript. how would i match it?
Oh, "[" and "]" also need to be matched.
so string like "[1]" or "[12345]" is a match.
Non match: "[23432" or "1]"
So for example:
$('.form .section .parent').find('input.text').each(function(index){
$(this).attr("name", $(this).attr("name").replace("[current]", "['"+index+"']"));
});
I need to replace input fields name: "items[0].firstname" to "items[1].firstname"
thanks
UPDATE: for your updated question
variable.match(/\[[0-9]+\]/);
Try this:
variable.match(/[0-9]+/); // for unsigned integers
variable.match(/[-0-9]+/); // for signed integers
variable.match(/[-.0-9]+/); // for signed float numbers
if("123".search(/^\d+$/) >= 0){
// its a number
}
I always use the following regular expression to detect any kind of number in a string. Had no issues so far.
'(([\+\-]*\d*\.*\d+[eE])?([\+\-]*\d*\.*\d+))'
In detail:
'([\+\-]*\d*\.*\d+)'
to match a (non-)decimal number with(out) leading digits or sign
'([\+\-]*\d*\.*\d+[eE])?'
to match an exponential base before the number.
If there are brackets around required, you can add them inside or outside of the surrounding paranthesis:
'(\[([\+\-]*\d*\.*\d+[eE])?([\+\-]*\d*\.*\d+)\])'
In fact the surrounding paranthesis are not necessary, but i keep them to easier concatenate the expression with others.
var mask = /^\d+$/;
if ( myString.exec(mask) ){
/* That's a number */
}
You can use the following function to find the biggest [number] in any string.
It returns the value of the biggest [number] as an Integer.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
DEMO
The following demo calculates the biggest number in your textarea every time you click the button.
It allows you to play around with the textarea and re-test the function with a different text.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
document.getElementById("myButton").addEventListener("click", function() {
alert(biggestNumber(document.getElementById("myTextArea").value));
});
<div>
<textarea rows="6" cols="50" id="myTextArea">
this is a test [1] also this [2] is a test
and again [18] this is a test.
items[14].items[29].firstname too is a test!
items[4].firstname too is a test!
</textarea>
</div>
<div>
<button id="myButton">Try me</button>
</div>
See also this Fiddle!

Delete first character of string if it is 0

I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...
TL;DR : Remove first character from the string:
str = str.substring(1);
...yes it is that simple...
Removing some particular character(s):
As #Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.
Use .charAt() and .slice().
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0 characters at the beginning, you can change the if() to a while().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
The easiest way to strip all leading 0s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0 character, as the question implies, you could use
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
Did you try the substring function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:
var cutOutZero = function(value) {
if (value.length && value.length > 0 && value[0] === '0') {
return value.substring(1);
}
return value;
};
http://jsfiddle.net/TRU66/1/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');

Categories