Reputation: 658
I am using javascript, and I am trying to work out how to select all characters of a word but no the first character.
For this, I am using regExpr. So the following expresion:
/\B[a-zA-Z'-]+/gi
should select all characters except the first one of each word, but it doesn't work for the text: "I'm a little tea pot" because of the apostrophe. I have tried everything, but dont know what else. I would apreciate any suggestion or support in this.
Thank you in advance!
Upvotes: 0
Views: 109
Reputation: 1
Edit, Updated
You can use String.prototype.split()
with RegExp
/^.{1}|\s[a-z'-](?!=\s){1}|\s/
to exclude first character in word, match remainder of word; for
loop, String.prototype.replace()
to replace matched words returned by .split()
following calling .toLowerCase()
on matched word.
var str = "I'M a liTtLe tEa pOt";
console.log("original string:", str);
var res = str.split(/^.{1}|\s[a-z'-](?!\s)|\s/)
.filter(Boolean); // `["'m", "ittle", "ea", "ot"]`
for (var i = 0; i < res.length; i++) {
str = str.replace(res[i], res[i].toLowerCase())
};
console.log("res array:", res, "replaced string:", str);
You can use String.prototype.slice()
with parameter 1
to return string excluding first character in str
console.log("I'm a little tea pot".slice(1))
or String.prototype.split()
and Array.prototype.slice()
to return array excluding first character in str
console.log("I'm a little tea pot".split("").slice(1))
Upvotes: 0
Reputation: 3786
s = "I'm a little tea pot, let's pour me out";
re = /(\B|')[a-z-']+/gi;
lastLettersArray = s.match(re);
console.log(lastLettersArray);
output
["'m", "ittle", "ea", "ot", "et's", "our", "e", "ut"]
Upvotes: 1
Reputation: 135
Try it here (Choose JS, PHP is default tab): http://regex.larsolavtorvik.com/
As simple as:
string.match(/\B\w+/gi);
Upvotes: 1
Reputation: 92854
Consider the following approach using String.split
and Array.slice
functions:
var str = "I'm a little tea pot", words = [];
str.split(" ").forEach((w) => w.length > 1 && words.push(w.slice(1)));
console.log(words); // ["'m", "ittle", "ea", "ot"]
Or by using RegExp.exec
function with regexp /\b\w([\w'-]+)\b/g
:
var str = "I'm a little tea pot", words = "", res, re = /\b\w([\w'-]+)\b/g;
while ((res = re.exec(str)) != null){
words += " " + res[1];
}
console.log(words); // "'m ittle ea ot"
Upvotes: 1
Reputation: 16112
A matching regular expression pattern is as follows:
https://regex101.com/r/rW9sX5/2/\b\S(\S+)/gi
Upvotes: 1