JavaScript split but keep last character in succinct way - javascript

I have a string that may or may not have a period and if it does I want to split on that and then add the period back. This is the code I have
let blurb = body.split('.')[0];
if (blurb.length > 1) {
blurb = blurb + '.';
}
I was hoping there is a more succinct and clear way to do this.

If you really just want to add it back without doing anything else...
let blurb = body.split('.').join('.');
But this is a no-op. Here's an obtuse version of your code, which may help clarify some things..
var body = "Some sentences. In a paragraph.",
bodySplit = body.split('.'), // ["Some sentences"," In a paragraph", ""],
firstSentence = bodySplit[0],
firstSentenceHasChars = firstSentence.length > 1,
blurb = null;
if (firstSentenceHasChars) {
blurb = firstSentence + ".";
} else {
// ?
}

Well you can use split with number of desired match in output as second parameter ( second parameter in split specifies number of splited element desired in output in our case you can add as 1 ).
console.log( 'blah.blah'.split('.', 1)[0] + '.' )
console.log( 'blahblah'.split('.', 1)[0] + '.' )

Here is a way to do it with String.replace() and a regex. You simply replace a dot followed by anything by a dot.
const dot = str => str.replace(/\..*$/, '.');
console.log(dot('hello. world'));
console.log(dot('bye bye.'));
console.log(dot('no dot here'));

I know this isn't everyone's cup of tea, but I went the regex route. This might make you ill though:
var str = 'blah.blah';
var reg = /([a-z]+)(.?)([a-z]*)/;
var arr = str.replace(reg, "$1,$3,$2").split(",").filter(s => s);
console.log(arr);
str = 'blahblah';
arr = str.replace(reg, "$1,$3,$2").split(",").filter(s => s);
console.log(arr);

I don't know where you want to go with this but I'd do:
"hohohosdsaeqwewe.kekekekekeke".replace(/([^.]*)\.([^.]*)/gi,(m,g1)=>g1+".")
if the sentence does not have any match, returns itself, if it does, then takes the first part(before the dot) and adds the dot back.

Related

How to remove a specific character from a string and put it back later when needed

For example
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "") //Thisismystring
Now that all the whitespaces have been removed, how do I put them back in the exact position?
Additionally, let's suppose the replaced string undergoes some change and becomes
let myChangedString = "(T)(h)(i)(s)(i)(s)(m)(y)(s)(t)(r)(i)(n)(g)";
Now I want to put the whitespaces back where they used to be i.e after (s) and before (i), after (s) and before (m), after (y) before (s)
I've spent a couple of hours on this and been stuck in the same position, any form of help would be greatly appreciated.
EDIT: Solved, thank you very much.
The trick here is to replace the spaces with another character - rather than just removing the space. That way - its a simple matter to replace the added character with a space to return the spaces to where they started. When I do this - I always use the tilde character "~" since it is easily recognisable as well as unlikely to actually be used in a string.
I have added a few variations / modifications as well as the example you have provided with every character being wrapped in parentheses - just note that you will need to escape these when replaceing the (~) for the " " space character.
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "~");
console.log(replacedString);//This~is~my~string
let modifiedString = replacedString.replace(/my/g, "your");
console.log(modifiedString);//This~is~your~string
let spacedString = modifiedString.replace(/~/g, " ");
console.log(spacedString);//This is your string
// using your example of wrapping each character in parentheses
let myChangedString = "(" + modifiedString.split('').join(")(") + ")";
console.log(myChangedString); //(T)(h)(i)(s)(~)(i)(s)(~)(y)(o)(u)(r)(~)(s)(t)(r)(i)(n)(g)
let mySpacedString = myChangedString.replace(/\(~\)/g, " ");
console.log(mySpacedString); //(T)(h)(i)(s) (i)(s) (y)(o)(u)(r) (s)(t)(r)(i)(n)(g)
Why not replace only the parts you need to be replaced?
For example search for word character and replace with the wanted parts.
console.log("This is my string".replace(/\w/g, '($&)'));
Better you just transform your original array. Loop through array and modify the char is not empty.
let myString = "This is my string";
let chars = [...myString].map(item => item !== ' ' ? '(' + item + ')': item)
console.log(chars.join(''))
Are you looking for this...
var result = "thisismystring".replace(/^(.{4})(.{2})(.{2})(.*)$/, "$1 $2 $3 $4");
alert(result);

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

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]);

Regex, grab only one instance of each letter

I have a paragraph that's broken up into an array, split at the periods. I'd like to perform a regex on index[i], replacing it's contents with one instance of each letter that index[i]'s string value has.
So; index[i]:"This is a sentence" would return --> index[i]:"thisaenc"
I read this thread. But i'm not sure if that's what i'm looking for.
Not sure how to do this in regex, but here's a very simple function to do it without using regex:
function charsInString(input) {
var output='';
for(var pos=0; pos<input.length; pos++) {
char=input.charAt(pos).toLowerCase();
if(output.indexOf(char) == -1 && char != ' ') {output+=char;}
}
return output;
}
alert(charsInString('This is a sentence'));
As I'm pretty sure what you need cannot be achieved using a single regular expression, I offer a more general solution:
// collapseSentences(ary) will collapse each sentence in ary
// into a string containing its constituent chars
// #param {Array} the array of strings to collapse
// #return {Array} the collapsed sentences
function collapseSentences(ary){
var result=[];
ary.forEach(function(line){
var tmp={};
line.toLowerCase().split('').forEach(function(c){
if(c >= 'a' && c <= 'z') {
tmp[c]++;
}
});
result.push(Object.keys(tmp).join(''));
});
return result;
}
which should do what you want except that the order of characters in each sentence cannot be guaranteed to be preserved, though in most cases it is.
Given:
var index=['This is a sentence','This is a test','this is another test'],
result=collapseSentences(index);
result contains:
["thisaenc","thisae", "thisanoer"]
(\w)(?<!.*?\1)
This yields a match for each of the right characters, but as if you were reading right-to-left instead.
This finds a word character, then looks ahead for the character just matched.
Nevermind, i managed:
justC = "";
if (color[i+1].match(/A/g)) {justC += " L_A";}
if (color[i+1].match(/B/g)) {justC += " L_B";}
if (color[i+1].match(/C/g)) {justC += " L_C";}
if (color[i+1].match(/D/g)) {justC += " L_D";}
if (color[i+1].match(/E/g)) {justC += " L_E";}
else {color[i+1] = "L_F";}
It's not exactly what my question may have lead to belive is what i wanted, but the printout for this is what i was after, for use in a class: <span class="L_A L_C L_E"></span>
How about:
var re = /(.)((.*?)\1)/g;
var str = 'This is a sentence';
x = str.toLowerCase();
x = x.replace(/ /g, '');
while(x.match(re)) {
x=x.replace(re, '$1$3');
}
I don't think this can be done in one fell regex swoop. You are going to need to use a loop.
While my example was not written in your language of choice, it doesn't seem to use any regex features not present in javascript.
perl -e '$foo="This is a sentence"; while ($foo =~ s/((.).*?)\2/$1/ig) { print "<$1><$2><$foo>\n"; } print "$foo\n";'
Producing:
This aenc

Categories