Basically I need to get the number of words in an input field. So the approach is to trim the leading and trailing spaces and also to limit the remaining spaces within the string to 1. So that I'll be able to get the number of words. Below is my code to do this.
E.g.
input value:
" Robert Neil Cook "
Expected output:
3 //"Robert Neil Cook"
This is what I tried.
var str = $.trim( $('#inval').val() );
var Fstr = str.split(' ').length;
console.log(fstr);
You can use below custom function for count words
function countWords(s){
s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude start and end white-space
s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
return s.split(' ').length;
}
alert(countWords("How are you?"));
Try below :
str= " Robert Neil Cook " ;
str = $.trim(str.replace(/ +(?= )/g,'')); // replace multiple spaces to single space
console.log(str)
var words = str.split(' '); // count the no of words using .split() method
alert(words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
You can use .match(/\S+/g):
var str = " Robert Neil Cook ";
var arr = str.match(/\S+/g);
var newstr = arr.join()
console.log('length::::>', arr.length);
console.log('newstr::::>', newstr);
This .match(/\S+/g) would return you the words without any space as an array and you can use length property of it.
Try this code..
var str = $.trim( $('#inval').val() );
var words = str.split(' ').filter(v=>v!='').length;
You can Haresh Vidja's function more compact like this
function countWords(s){
return s.trim().replace(/[ ]{2,}/gi," ").split(" ").length;
}
console.log(countWords("some words here")
Please have a look attached snippet.
var str = $.trim( $('#inval').val() );
str1 = str.replace(/ +(?= )/g,'')
var fstr = str1.split(' ').length;
console.log(fstr);
console.log(str1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value=" Robert Neil Cook " id="inval">
Very simple solution, try this
var str = " Robert Neil Cook ";
str = str.trim();
var str = str.split(' ').join('');
var fstr = str.split(' ').length;
console.log(fstr);
Related
So I made a method to make the first letter of all the words in any string Uppercase.
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
let newStr = strArray.toString();
let finalStr = newStr.replace(/,/g, " ");
return finalStr;
};
The problem with this is when I pass a string that has real commas(,) it replace that comma(,) too in the finalStr step. For e.g
console.log("How can mirrors be real, if our eyes aren't real".toMyCase(); gives me
How Can Mirrors Be Real If Our Eyes Aren't Real (there are two spaces after Real).
You can use strArray.join(' ');
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
return strArray.join(' ');
};
console.log("How can mirrors be real, if our eyes aren't real".toMyCase());
How about with this single line soln after string split(), uppercase first character and join the rest using .map() with the first?,
let str = "How can mirrors be real, if our eyes aren't real";
let captialized_words = str => str.split(' ').map(w => w.substring(0, 1).toUpperCase() + w.substring(1)).join(' ')
console.log(captialized_words(str))
Instead of
let finalStr = newStr.replace(/,/g, " ");
Do
let finalStr = newStr.replace(/,/g, "");
I want to split a string based on the delimiters " " and "," (including quotation marks). How would I be able to do this? I tried doing this:
var str = '"String","String2" "String3"';
str = str.split('" "', '","');
console.log(str);
But it didn't work. I was expecting this console output:
["String", "String2", "String3"]
But I got:
[]
How do I split a string based on two delimiters? Is it possible?
let str = '"String","String2" "String3"';
str = str.split(/ |,/);
console.log(str);
let str2 = '"String","String2" "String3"';
str2 = str2.split(/" "|","|"|\n/).filter(Boolean);
console.log(str2);
let str3 = '"String","String2" "String3"';
str3 = str3.match(/[\w\d]+/g);
console.log(str3);
You can specify regex or array as delimiter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
try below solution
var str = '"String","String2" "String3"';
str = str.match(/\w+|"[^"]+"/g)
str = str.map(function(x){return x.replace(/"/g, '');});
console.log('Final str : ', str);
You can use regex: str = str.split(/,| /)
console.log("a,b c".split(/,| /));
I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")
I'm trying to replace all of the leading spaces in a string with something
Here's what I tried so far
var str = ' testing 1 2 3 ',
regex = /^\s*/,
newStr = str.replace(regex, '.');
document.write(newStr)
I want to get a result like:
'.....testing 1 2 3 '
Is there something I'm missing?
Try this:
var s = " a b c";
print(s.replace(/^\s+/, function(m){ return m.replace(/\s/g, '.');}));
which prints:
...a b c
Alternative (ignores strnigs w/ no non-space)
var newStr = "";
newStr = (newStr = Array(str.search(/[^\s]/) + 1).join(".")) + str.substr(newStr.length);
What about:
/^([ ]+)/
I'm not sure \s does the trick, while a plain should be able to handle this!
This is even shorter.
var text = " a b c";
var result = s.replace(/\s/gy, ".");
console.log(result); // prints: "...a b c";
Why it works was explained for me here.
Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c';
console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
This will replace it with the contents of the variable replacement:
var str = 'a_b_c',
replacement = '!';
console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"
// Replace last char in a string
console.log(
str1.substring(0,str1.length-2)+"?"
)
// alternative syntax
console.log(
str1.slice(0,-1)+"?"
)
// Replace last underscore in a string
var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax
console.log(
str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)
What about this?
function replaceLast(x, y, z){
var a = x.split("");
a[x.lastIndexOf(y)] = z;
return a.join("");
}
replaceLast("Hello world!", "l", "x"); // Hello worxd!
Another super clear way of doing this could be as follows:
let modifiedString = originalString
.split('').reverse().join('')
.replace('_', '')
.split('').reverse().join('')
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
var someString = "(/n{})+++(/n{})---(/n{})$$$";
var toRemove = "(/n{})"; // should find & remove last occurrence
function removeLast(s, r){
s = s.split(r)
return s.slice(0,-1).join(r) + s.pop()
}
console.log(
removeLast(someString, toRemove)
)
Breakdown:
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
Reverse the string, replace the char, reverse the string.
Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?
// Define variables
let haystack = 'I do not want to replace this, but this'
let needle = 'this'
let replacement = 'hey it works :)'
// Reverse it
haystack = Array.from(haystack).reverse().join('')
needle = Array.from(needle).reverse().join('')
replacement = Array.from(replacement).reverse().join('')
// Make the replacement
haystack = haystack.replace(needle, replacement)
// Reverse it back
let results = Array.from(haystack).reverse().join('')
console.log(results)
// 'I do not want to replace this, but hey it works :)'
This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array)
Anyway, I just thought I'd put it out there in case someone prefers it.
var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'
The '_' can be swapped out with the char you want to replace
And the '-' can be replaced with the char or string you want to replace it with
You can use this code
var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);
alert(str);
This is a recursive way that removes multiple occurrences of "endchar":
function TrimEnd(str, endchar) {
while (str.endsWith(endchar) && str !== "" && endchar !== "") {
str = str.slice(0, -1);
}
return str;
}
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)