I would like to remove the characters destructively from two points in a string, so when the string is called after the removal it would not include the removed characters.
Example
var string = "I am a string";
I'd like to: remove (0, 7);
When I call string again it should return:
console.log(string) => string
Example-2
var string = "I am a string";
I'd like to: remove (7, 10);
When I call string again it should return:
console.log(string) => I am a ing
See javascript substring.
For your example use this:
var string = "I am a string";
console.log(string.substring(7));
OUTPUTS
string
UPDATE
For removing a portionof a string, you can do it by concating the first wanted characters with the last wanted characters, something like this:
var string = "I am a string";
console.log(string.substr(0, 5) + string.substr(7));
OUTPUTS
I am string
If you want to have a direct function for removing portions of strings, see Ken White's answer that uses substr instead of substring. The difference between substr and substring is in the second parameter, for substring is the index to stop and for substr the length to return. You can use something like this:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
string.replaceAt(5, 2); // Outputs: "I am string"
Or if you want to use start and end like (7, 10), then have a function like this:
String.prototype.removeAt = function(start, end) {
return this.substr(0, start) + this.substr(end);
}
string.removeAt(7, 10); // Outputs: "I am a ing"
The easiest way is to just slice the front part and the back part and splice them back together:
var string = "I am a string";
string = string.substring(0, 7) + string.substring(10);
console.log(string);
// => I am a ing
Related
I'm new to programming and would like to extract a string from certain an index up to a whitespace character.
Consider string "hello world from user"
and the cursor position is at index 6. From index 6, I want to extract string the string up until the whitespace character so the output would be "world". How can I achieve this?
I have tried using:
cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position,
event.target.value.indexOf(' '));
But this second position for extracting string doesn't seem to be correct. Could someone help me with extracting the string from the cursor's position to the white space character?
Thanks.
First you need to get the string from the cursor position to the end of the string.
Afterwards you can chain another .substr() call to trim the string from the beginning to the first occurence of a whitespace.
Here's an example:
var str = "hello world from user";
var cursorPosition = 6;
str = str.substr(cursorPosition, str.length).substr(0, str.indexOf(' '));
console.log(str);
You can use .slice() to cut the string from your starting index to the end of the word, and then use .split() on your new string to "chunk" it into an array where each element is a word separated from the string separated by a space.
Eg:
"hello world from user" --> slice(6) --> "world from user"
Then:
"world from user" --> split(' ') --> ["world", "from", "user"]
Getting the first element/word (index 0) from the split array will give "word"
See example below:
const str = "hello world from user";
const idx = 6;
const res = str.slice(idx).trim().split(' ')[0];
console.log(res); // "world"
If you need it such that when you start on a space you get the next word, you can use .trim() before you .split() the array:
const str = "hello world from user";
const idx = 5;
const res = str.slice(idx).trim().split(' ')[0];
console.log(res); // "world"
You can achieve it this way
cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position);
next_word_length = extracted_string.split(' ')[0].length
next_word = event.target.value.substr(cursor_position, next_word_length)
indexOf takes fromIndex as a second argument. So no need to have all those chainings. You can simply use the function below.
const extract = (str, startIndex, search = " ") => str.slice(startIndex, str.indexOf(search, startIndex));
const myString = extract("hello world from user", 6);
console.log(myString);
// Output: "world"
I want truncate the string if contains a word that is longer than a certain value. For example, if the string is this one:
"test fassfsaf longstring 1112faffasfsaffasfssafssssafafsas"
and i want truncate the string if a word have size > 8 then the result must be:
"test fassfsaf longstri"
Any suggestion?
split the string using split(" ") will return you an array of words. you can use filter() here, accept elements till first word with length>8. to make the string back use join(" ") on filter array of words.
var str = "test fassfsaf longstring 1112faffasfsaffasfssafssssafafsas";
str = str.split(" ");
str = str.filter((x, index, arr) => !(x.length > 8 && arr[index-1].length > 8));
str[str.length - 1] = str[str.length - 1].substr(0,8);
console.log(str.join(" "));
Try with split() the string using " ".Then recreate the array with map using slice(0,8) condition.And finally, join() the string with " "
var a="test fassfsaf longstring 1112faffasfsaffasfssafssssafafsas";
var r = a.split(' ').map(i=> i.slice(0,8));
console.log(r.join(" "))
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]);
I'm trying to insert some whitespace in a string if the string conforms to a certain format. Specifically, if the string consists of only numbers, and is exactly five characters in length, whitespace should be added between the third and fourth numbers.
Here's my test case:
function codeAddress() {
var num_regex = /^\d+$/,
input = $("#distributor-search").val(),
address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;
console.log('The address is: ' + address);
return false;
}
For some reason, chaining .split(), .splice() and .join() seems to not return anything. Where am I going wrong?
split() returns an array, splice() returns the array with the removed elements and join() returns the joined array like they should.
Looks like everything goes wrong at splice(). Instead of giving the remainders, you get the removed items.
My test:
var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');
console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values
You could solve this by making a prototype that uses splice's functionality, like so:
Array.prototype.isplice = function() {
var tmp = this;
Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);
return tmp;
};
var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected
As others have explained, your function didn't work because .splice() returns the removed elements, instead of the resulting array.
Try using this regex, instead:
/^(\d\d\d)(\d\d)$/
It will only match a string if it's 5 digits long, it won't modify other strings.
Examples:
var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"
So, in your case:
address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
Why not just use the regex itself?
var num_regex = /^(\d\d\d)(\d\d)$/,
input = $("#distributor-search").val(),
address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];
That regex matches a five-digit string and groups the first three and last two digits together. If the test string matches, then the .match() function returns an array with the two groups in positions 1 and 2 (position 0 being the entire match).
You can't concatenate splice with join in your case:
splice(3, 0 , ' ').join()
remember that splice returns a new array containing the removed items, not the result array.
How can I replace a substring of a string given the starting position and the length?
I was hoping for something like this:
var string = "This is a test string";
string.replace(10, 4, "replacement");
so that string would equal
"this is a replacement string"
..but I can't find anything like that.
Any help appreciated.
Like this:
var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length);
You can add it to the string's prototype:
String.prototype.splice = function(start,length,replacement) {
return this.substr(0,start)+replacement+this.substr(start+length);
}
(I call this splice because it is very similar to the Array function of the same name)
For what it's worth, this function will replace based on two indices instead of first index and length.
splice: function(specimen, start, end, replacement) {
// string to modify, start index, end index, and what to replace that selection with
var head = specimen.substring(0,start);
var body = specimen.substring(start, end + 1); // +1 to include last character
var tail = specimen.substring(end + 1, specimen.length);
var result = head + replacement + tail;
return result;
}
Short RegExp version:
str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word);
Example:
String.prototype.sreplace = function(start, length, word) {
return this.replace(
new RegExp("^(.{" + start + "}).{" + length + "}"),
"$1" + word);
};
"This is a test string".sreplace(10, 4, "replacement");
// "This is a replacement string"
DEMO: http://jsfiddle.net/9zP7D/
The Underscore String library has a splice method which works exactly as you specified.
_("This is a test string").splice(10, 4, 'replacement');
=> "This is a replacement string"
There are a lot of other useful functions in the library as well. It clocks in at 8kb and is available on cdnjs.