How to get the last alphabetic character in string? - javascript

Here, I want to give each character a space except for the last alphabetic one:
var str = "test"
var result = "";
for (var i = 0; i < str.length; i++) {
result += (/*condition*/) ? str[i]
: str[i] + " ";
}
console.log(result);
So it prints "t e s t".
I tried this (i === str.length - 1) but it didn't work when a string had period(.) as it's last character ("test.") while I wanna target only alphabetics.

You can use a regular expression to remove all non-alphabetical characters first, and then do a split/join combination to insert the spaces (or use another regex):
var str = "don't test.";
var result = str.replace(/[^a-z]/gi, '').split('').join(' ');
console.log(result);

"testasdf. asdf asdf asd.d?".replace(/./g,"$& ").replace(/([A-Za-z]) ([^A-Za-z]*)$/, '$1$2')
the first replace add a space to all char
the second replace removes the space after the last letter
console.log("testasdf?".replace(/./g,"$& ").replace(/([A-Za-z]) ([^A-Za-z]*)$/, '$1$2'));
console.log("Super test ! Yes".replace(/./g,"$& ").replace(/([A-Za-z]) ([^A-Za-z]*)$/, '$1$2'));

There is such a feature like lookahead assertions.
So it could be
str.replace(/(\w)(?=.*\w)/, "$1")

Using a regex replace function, you can space out all of your characters like this:
"test string, with several words.".replace(/\w{2,}/g, match => match.split('').join(' '))
Explanation
\w{2,} match 2 or more alphabetic characters
match.split('').join(' ') split each match into characters, and rejoin with spaces between

Related

limit character number for specific words starting with # in JavaScript

I have some issues, I need to "limit" character for specific word with special character (10 characters)
example in a textarea :
The #dog is here, I need a #rest and this is not #availableeeeeeeee for now
the word "availableeeeeeeee" needs to be cut when I reach 10 characters
Desired results
The #dog is here, I need a #rest and this is not #availablee for now
My question is how to limit characters for each word that containing a hashtag?
Thanks
1. Regex Solution:
You can use .replace() method with the following regex /(#\w{10})\[\w\d\]+/g, it will remove the extra characters:
str = str.replace(/(#\w{10})[\w\d]+/g, '$1');
Demo:
var str = "The #dog is here, I need a #rest and this is not #availableeeeeeeee for now";
str = str.replace(/(#\w{10})[\w\d]+/g, '$1');
console.log(str);
Note:
This regex matches the words starting with # using a matching group to get only the first 10 characters.
Full match #availableeeeeeeee
Group 1. n/a #availablee
And the .replace() call will keep only the matched group from the regex and skip the extra characters.
Note that you need to attach this code in the onchange event handler of your textarea.
2. split() Solution:
If you want to go with a solution that doesn't use Regex, you can use .split() method with Array.prototype.map() like this:
str = str.split(" ").map(function(item){
return item.startsWith("#") && item.length > 11 ? item.substr(0,11) : item;
}).join(" ");
Demo:
var str = "The #dog is here, I need a #rest and this is not #availableeeeeeeee for now";
str = str.split(" ").map(function(item){
return item.startsWith("#") && item.length > 11 ? item.substr(0,11) : item;
}).join(" ");
console.log(str);
a simple solution with javascript could be, to split text area all words into array. iterate it and validate word length.
var value = $('#text').val();
var maxSize = 10;
var words = value.trim().replace(regex, ' ').split(' ');
for(var wlength= 0 ; wlength < words.length; wlength++)
{
if(words[wlength] > maxSize)
{
alert('size exceeds max allowed');
}
}
you can try not allowing typing itself after 10 characters for any word by regular expression inline validation in HTML directly.
Well, I think you can try the following.
Using split() method will cut the string in words, then forEach word if it startsWith a '#', we substr it up to 10 + 1 characters. Finally, join everybody to obtain the final result :).
string="The #dog is here, I need a #rest and this is not #availableeeeeeeee for now"
var result = []
string.split(" ").forEach(function(item){
if (item.startsWith("#")){
result.push(item.substr(0,11));
} else result.push(item);
});
console.log(result.join(" "));

How to reverse a string in place without reversing the punctuation?

I am trying to reverse the words in a string without any effect on punctuation.
This is my current code:
function reverse(str) {
str = str.split("").reverse().join("");
str = str.split(" ").reverse().join(" ");
console.log(str)
};
reverse("This is fun, hopefully.")
The result of the above function is sihT si ,nuf .yllufepoh
while I am trying to to get it like sihT si nuf, yllufepoh.
Another approach is to replace all sequences of letters with their reversed forms using replace and a regular expression, e.g.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
document.write(reverseWords("This is fun, hopefully.")); // sihT si nuf, yllufepoh.
If you wish to include numbers as word characters (w.g. W3C), then the regular expression should be:
/\w+/g
Split the sentence on word boundaries, which doesn't consume any of the string,
then split each word into its letters (non-spaces with \S) using a lookahead ?= so those aren't consumed.
Reverse the array of the letters, then rejoin them with no separator .join("")
and finally rejoin the sentence, again with no separator because the spaces between the words were retained when originally splitting on word boundaries.
var sentence = "This is fun, hopefully.";
sentence.split(/\b/)
.map(w => w.split(/(?=\S)/)
.reverse()
.join("") )
.join("");
Doing this in Chrome's javascript console produced the output:
"sihT si nuf, yllufepoh."
Note this doesn't correctly handle a run of punctuation. For example hopefully!? would become yllufepoh?!, reversing the punctuation too.
You can do better with Regular Expressions, but this is a simple solution that I just wrote.
function reverse(str){
var out = '';
var word = '';
for (var i=0;i<str.length;i++) {
// your punctuation characters
if (',.!? '.indexOf(str[i]) == -1) word += str[i];
else {
out += word.split('').reverse().join('');
out += str[i];
word = '';
}
}
return out;
};
console.log(reverse("This is fun, hopefully."));

Javascript regex parsing dots and whitespaces

In Javascript I have several words separated by either a dot or one ore more whitepaces (or the end of the string).
I'd like to replace certain parts of it to insert custom information at the appropriate places.
Example:
var x = "test1.test test2 test3.xyz test4";
If there's a dot it should be replaced with ".X_"
If there's one or more space(s) and the word before does not contain a dot, replace with ".X "
So the desired output for the above example would be:
"test1.X_test test2.X test3.X_xyz test4.X"
Can I do this in one regex replace? If so, how?
If I need two or more what would they be?
Thanks a bunch.
Try this:
var str = 'test1.test test2 test3.xyz test4';
str = str.replace(/(\w+)\.(\w+)/g, '$1.X_$2');
str = str.replace(/( |^)(\w+)( |$)/g, '$1$2.X$3');
console.log(str);
In the first replace it replaces the dot in the dotted words with a .X_, where a dotted word is two words with a dot between them.
In the second replace it adds .X to words that have no dot, where words that have no dot are words that are preceded by a space OR the start of the string and are followed by a space OR the end of the string.
To answer this:
If there's a dot it should be replaced with ".X_"
If there's one or more spaces it should be replaced with ".X"
Do this:
x.replace(/\./g, '.X_').replace(/\s+/g, '.X');
Edit: To get your desired output (rather than your rules), you can do this:
var words = x.replace(/\s+/g, ' ').split(' ');
for (var i = 0, l = words.length; i < l; i++) {
if (words[i].indexOf('.') === -1) {
words[i] += ".X";
}
else {
words[i] = words[i].replace(/\./g, '.X_');
}
}
x = words.join(' ');
Basically...
Strip all multiple spaces and create an array of "words"
Loop through each word.
If it doesn't have a period in it, then add ".X" to the end of the word
Else, replace the periods with ".X_"
Join the "words" back into a string and separate it by spaces.
Edit 2:
Here's a solution using only javascript's replace function:
x.replace(/\s+/g, ' ') // replace multiple spaces with one space
.replace(/\./g, '.X_') // replace dots with .X_
// find words without dots and add a ".X" to the end
.replace(/(^|\s)([^\s\.]+)($|\s)/g, "$1$2.X$3");

Remove last comma (and possible whitespaces after the last comma) from the end of a string

Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code.
I got a working fiddle. But it has a bug.
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged
var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma
var str = 'This is a test, ';
alert( removeLastComma(str) ); // should remove the last comma
function removeLastComma(strng){
var n=strng.lastIndexOf(",");
var a=strng.substring(0,n)
return a;
}
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The / mark the beginning and end of the regular expression
The , matches the comma
The \s means whitespace characters (space, tab, etc) and the * means 0 or more
The $ at the end signifies the end of the string
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {
var strVal = $.trim($('.txtValue').text());
var lastChar = strVal.slice(-1);
if (lastChar == ',') { // check last character is string
strVal = strVal.slice(0, -1); // trim last character
$("#demo").text(strVal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="txtValue">Striing with Commma,</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
function removeLastComma(str) {
return str.replace(/,(\s+)?$/, '');
}
In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");
It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '
https://jsfiddle.net/dc8moa3k/
long shot here
var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true) {
currentIndex=pattern.lastIndex;
}
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
alert(sentence);
Remove last comma. Working example
function truncateText() {
var str= document.getElementById('input').value;
str = str.replace(/,\s*$/, "");
console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>
First, one should check if the last character is a comma.
If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);
To remove the last comma from a string, you need
text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')
See the regex demo. Details:
,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string.
,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma.
See the JavaScript demo:
const text = '1,This is a test, and this is another, ...';
console.log(text.replace(/,(?=[^,]*$)/, ''));
console.log(text.replace(/,(?![^,]*,)/, ''));
Remove whitespace and comma at the end use this,
var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"
The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.
With or without Regex.
I suggest two processes and also consider removing space as well. Today I got this problem and I fixed this by writing the below code.
I hope this code will help others.
//With the help of Regex
var str = " I am in Pakistan, I am in India, I am in Japan, ";
var newstr = str.replace(/[, ]+$/, "").trim();
console.log(newstr);
//Without Regex
function removeSpaceAndLastComa(str) {
var newstr = str.trim();
var tabId = newstr.split(",");
strAry = [];
tabId.forEach(function(i, e) {
if (i != "") {
strAry.push(i);
}
})
console.log(strAry.join(","));
}
removeSpaceAndLastComa(str);
If you are targeting es6, then you can simply do this
str = Array.from( str ).splice(0, str.length - 1).join('');
This Array.from(str) converts the string to an array (so we can slice it)
This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array
This join('') joins the entries in the array to form a string
Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this
str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;

Regex won't match words as expected

I am trying to use XRegExp to test if a string is a valid word according to these criteria:
The string begins with one or more Unicode letters, followed by
an apostrophe (') followed by one or more Unicode letters, repeated 0 or more times.
The string ends immediately after the matched pattern.
That is, it will match these terms
Hello can't Alah'u'u'v'oo O'reilly
but not these
eatin' 'sup 'til
I am trying this pattern,
^(\\p{L})+('(\\p{L})+)*$
but it won't match any words that contain apostrophes. What am I doing wrong?
EDIT: The code using the regex
var separateWords = function(text) {
var word = XRegExp("(\\p{L})+('(\\p{L})+)*$");
var splits = [];
for (var i = 0; i < text.length; i++) {
var item = text[i];
while (i + 1 < text.length && word.test(item + text[i + 1])) {
item += text[i + 1];
i++;
}
splits.push(item);
}
return splits;
};
I think you will need to omit the string start/end anchors to match single words:
"(\\p{L})+('(\\p{L})+)*"
Also I'm not sure what those capturing groups are needed for (that may depend on your application), but you could shorten them to
"\\p{L}+('\\p{L}+)*"
Try this regex:
^[^'](?:[\w']*[^'])?$
First it checks to ensure the first character is not an apostrophe. Then it either gets any number of word characters or apostrophes followed by anything other than an apostrophe, or it gets nothing (one-letter word).

Categories