How can I remove the last word in the string using JavaScript?
For example, the string is "I want to remove the last word."
After using removal, the string in the textbox will display "I want to remove the last"
I've seen how to remove the last character using the substring function, but because the last word can be different every time. Is there a way to count how many words are required to remove in JavaScript?
Use:
var str = "I want to remove the last word.";
var lastIndex = str.lastIndexOf(" ");
str = str.substring(0, lastIndex);
Get the last space and then get the substring.
An easy way to do that would be to use JavaScript's lastIndexOf() and substr() methods:
var myString = "I want to remove the last word";
myString = myString.substring(0, myString.lastIndexOf(" "));
You can do a simple regular expression like so:
"I want to remove the last word.".replace(/\w+[.!?]?$/, '')
>>> "I want to remove the last"
Finding the last index for " " is probably faster though. This is just less code.
Following answer by Amir Raminfar, I found this solution. In my opinion, it's better than accepted answer, because it works even if you have a space at the end of the string or with languages (like French) that have spaces between last word and punctuation mark.
"Je veux supprimer le dernier mot !".replace(/[\W]*\S+[\W]*$/, '')
"Je veux supprimer le dernier"
It strips also the space(s) and punctuation marks before the last word, as the OP implicitly required.
Peace.
Fooling around just for fun, this is a funny and outrageous way to do it!
"I want to remove the last word.".split(" ").reverse().slice(1).reverse().join(" ")
Use the split function:
var myString = "I want to remove the last word";
var mySplitResult = myString.split(" ");
var lastWord = mySplitResult[mySplitResult.length-1]
The shortest answer to this question would be as below,
var str="I want to remove the last word".split(' ');
var lastword=str.pop();
console.log(str.join(' '));
You can match the last word following a space that has no word characters following it.
word=/s+\W*([a-zA-Z']+)\W*$/.exec(string);
if(word) alert(word[1])
If anyone else here is trying to split a string name in to last name and first name, please make sure to handle the case in which the name has only word.
let recipientName = _.get(response, 'shipping_address.recipient_name');
let lastWordIndex = recipientName.lastIndexOf(" ");
let firstName = (lastWordIndex == -1) ? recipientName : recipientName.substring(0, lastWordIndex);
let lastName = (lastWordIndex == -1) ? '' : recipientName.substring(lastWordIndex + 1);
To get the last word
const animals = "I want to remove the last word.".split(" ");
console.log(animals.slice(-1));
Expected output: word.
To remove the last word
console.log(animals.slice(0, -1).join(" ");
Expected output: "I want to remove the last"
Related
in order to explain myself better.
I have the following string
var a = 'Dg_DQ_DA'
And i pass for example DQ
I want to check if string a contains DQ, that i can do, but also i want to check DQ next character, or know what character is only if it matches, i'm kinda stuck on how to do that dumb thing.
Thanks.
As pointed out by soktinpk, you can concatenate the "needle" string with "_", and use indexOf as usual:
haystack.indexOf(needle + "_") != -1
Try this.
var str = 'Dg_DQ_DA';
//check if string a contains DQ
if(/DQ/g.test(str)){
var nst = str.match(/DQ./g);
console.log(nst[0].slice(-1)); //To get the last character
}else{
//Not Found
}
The result of console will be:
_
I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
jQuery.trim() works well.
http://api.jquery.com/jQuery.trim/
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
I want to replace multiple occurences of whitespace inside the string with a single space
...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join("");
alert(x);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
create a JQuery function .
this is key press event.
Initialize a variable.
Give condition to match the character
show a alert message for your matched condition.
I am doing some logic for the last word that is on the sentence. Words are separated by either space or with a '-' character.
What is easiest way to get it?
Edit
I could do it by traversing backwards from the end of the sentence, but I would like to find better way
Try splitting on a regex that matches spaces or hyphens and taking the last element:
var lastWord = function(o) {
return (""+o).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lastWord('This is a test.'); // => 'test.'
lastWord('Here is something to-do.'); // => 'do.'
As #alex points out, it's worth trimming any trailing whitespace or hyphens. Ensuring the argument is a string is a good idea too.
Using a regex:
/.*[\s-](\S+)/.exec(str)[1];
that also ignores white-space at the end
Have you tried the lastIndexOf function http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
Or Split function http://www.w3schools.com/jsref/jsref_split.asp
Here is a similar discussion have a look
You can try something like this...
<script type="text/javascript">
var txt = "This is the sample sentence";
spl = txt.split(" ");
for(i = 0; i < spl.length; i++){
document.write("<br /> Element " + i + " = " + spl[i]);
}
</script>
Well, using Split Function
string lastWord = input.Split(' ').Last();
or
string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];
While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.
string input = ".... ,API";
here, the comma would be part of the "word".
Also, if the first method of obtaining the word is correct, ie. everything after the last space, and your string adheres to the following rules:
Will always contain at least one space
Does not end with one or more space (in case of this you can trim it)
then you can use this code that will allocate fewer objects on the heap for GC to worry about later:
string lastWord = input.Substring(input.LastIndexOf(' ') + 1);
I hope its help
Okay I have a simple Javascript problem, and I hope some of you are eager to help me. I realize it's not very difficult but I've been working whole day and just can't get my head around it.
Here it goes: I have a sentence in a Textfield form and I need to reprint the content of a sentence but WITHOUT spaces.
For example: "My name is Slavisha" The result: "MynameisSlavisha"
Thank you
You can replace all whitespace characters:
var str = "My name is Slavisha" ;
str = str.replace(/\s+/g, ""); // "MynameisSlavisha"
The /\s+/g regex will match any whitespace character, the g flag is necessary to replace all the occurrences on your string.
Also, as you can see, we need to reassign the str variable because Strings are immutable -they can't really change-.
Another way to do it:
var str = 'My name is Slavisha'.split(' ').join('');
I'm using regular expression to count the total spaces in a line (first occurrence).
match(/^\s*/)[0].length;
However this reads it from the start to end, How can I read it from end to start.
Thanks
You can do this:
function reverse(str) {
return str.split('').reverse().join('');
}
To use it:
var str = 'Hello World';
alert(reverse(str));
How it works, we split the string by an empty character to turn it into an array, then we reverse the order of the array, then we join it all back together, using no character as the glue. So we get alerted dlroW olleH
Are you trying to find the number of trailing spaces on a line?
s.match(/\s*$/)[0].length;
Or last spaces found, even if there's something else trailing:
s.match(/(\s*)[^\s]*$/)[1].length
do you just want to know how many chars there is before the space? If so, does this not suit your needs.
var str = 'The quick brown fox jumps';
var first = str.indexOf(' ');
var last = str.lastIndexOf(' ');
alert('first space is at: ' + first + ' and last space is at: ' + last);
I'm using regular expression to count the total spaces in a line
Then why do you care about which way it counts? "aaa" contains 3 a's whether I start from the first or last one. 3 is still 3...