I want to get a portion of a string via .substring(indexStart, indexEnd) then replace the same portion in the original string.
var portion = "my new house".substring(3, 6),
portion = "old";
// what's next?
You could take the surrounding substrings and concatenate:
var str = "my new house";
str = str.slice(0, 3) + "old" + str.slice(6);
console.log(str); // "my old house"
Of course, this is assuming you want to replace parts of the string marked off by certain indeces. If you just want to replace a word, you would use:
str = str.replace(/new/g, 'old');
(Omit the global flag to only replace the first occurrence.)
You just need to call 'replace' on the original string to find the substring you gathered and replace it with the new desired string.
var oldString = "my new house my new house";
var subStr = oldString.substring(indexStart, indexEnd);
var newValue = "old";
var newString = oldString.replace(subStr, newValue);
Related
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
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 to get substring from string at last index match space and put it into another string :
for example
if I have : var string1="hello any body from me";
in string1 I have 4 spaces and I want to get the word after last spaces in string1 so here I want to get the word "me" ...
I don't know number of spaces in string1 ... so How I can get substring from string after last seen to specific characer like space ?
You could try something like this using the split method, where input is your string:
var splitted = input.split(' ');
var s = splitted[splitted.length-1];
var splitted = "hello any body from me".split(' ');
var s = splitted[splitted.length-1];
console.log(s);
Use split to make it an array and get the last element:
var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);
Or just :
var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me
Thank's to reverse method
I'd use a regular expression to avoid the array overhead:
var string1 = "hello any body from me";
var matches = /\s(\S*)$/.exec(string1);
if (matches)
console.log(matches[1]);
You can use split method to split the string by a given separator, " " in this case, and then get the final substring of the returned array.
This is a good method if you want to use other parts of the string and it is also easily readable:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator
var splitString = string1.split(" ");
// get the last substring from the array
var lastSubstr = splitString[splitString.length - 1];
// this will log "me"
console.log(lastSubstr);
// ...
// oh i now actually also need the first part of the string
// i still have my splitString variable so i can use this again!
// this will log "hello"
console.log(splitString[0]);
This is a good method without the need for the rest of the substrings if you prefer to write quick and dirty:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator, reverse it, and then select the first substring
var lastSubstr = string1.split(" ").reverse()[0];
// this will log "me"
console.log(lastSubstr);
Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final
How do i replace the text with each method?
Is it right? it doesnt replace / find the text correctly
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style;
$(style_find).each(function(i,cl){
new_style = cur_style.replace(cl,'new-class');
// it doesnt replace the whole word
});
})
String.prototype.replace() behaves differently depending upon the type of it's first parameter. Consider this code:
var example = "str str str str";
example = example.replace("str", "bob");
console.log(example === "bob str str str"); // === true?
I gave replace() a string for it's first parameter. When you do so, it only replaces the first occurrence of the substring.
When you call replace() with a RegExp you get something that returns all matches replaced
var example = "str str str str";
example = example.replace(/str/g, "bob");
console.log(example === "bob bob bob bob"); // === true
What we need is a regexp that matches everything you want to replace.
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var regexp = (function() {
var inner = "";
style_find.forEach(function(el) {
inner = inner + el + "|";
});
return new RegExp(inner, "g");
}());
With regexp I can modify your code to:
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style = cur_style.replace(regexp, 'new-class');
});