How can I replace a string by range? - javascript

I need to replace a string by range
Example:
string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";
but this need to be dinamically. Cant be replace a fixed word ...need be by range
I have tried
result = string.replaceAt(0, 'that');
but this replace only the first character and I want the first to third

function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
var str = "this is a string";
var newString = replaceRange(str, 0, 4, "that"); // "that is a string"

var str = "this is a string";
var newString = str.substr(3,str.length);
var result = 'that'+newString
substr returns a part of a string, with my exemple, it starts at character 3 up to str.length to have the last character...
To replace the middle of a string, the same logic can be used...
var str = "this is a string";
var firstPart = str.substr(0,7); // "this is "
var lastPart = str.substr(8,str.length); // " string"
var result = firstPart+'another'+lastPart; // "this is another string"

I simple substring call will do here
var str = "this is a string";
var result = "that" + str.substring(4);
Check out a working jsfiddle.

Related

Splitting sentence doesn't work if I am trying to split the last word

I'm trying to split a sentence by removing a certain word
for example:
var word = "am";
var sentence = "Hello am I John?";
var stringpart2 = sentence.split(" ");
var stringpart1 = stringpart2.splice(0,stringpart2.indexOf(word));
stringpart2.remove(word);
stringpart1.remove(word);
var istring1 = stringpart1.toString();
var finalpart1 = istring1.replace(/,/g, " ");
var istring2 = stringpart2.toString();
var finalpart2 = istring2.replace(/,/g, " ");
now this works as it returns this:
finalpart1 = "Hello I"
finalpart2 = "John?"
but when I make the word the last word in the sentence:
var word = "John";
it returns
finalpart1 = ""
finalpart2 = "Hello am I John?"
Anyone have any idea how to fix this so its like this:
finalpart1 = "Hello am I?"
finalpart2 = ""
It might be worth mentioning I'm taking the word and the sentence out of an array that I get through $.getJSON and if the word is the first word of the sentence it works just fine.
You may use the following regular expression:
function replace(text, word) {
return text.replace(new RegExp('\\s\\b' + word + '|' + word + '\\b\\s'), '')
}
const text = 'Hello am I John?'
console.log( replace(text, 'Hello') )
console.log( replace(text, 'am') )
console.log( replace(text, 'John') )
You can split directly by the word:
var splitted = sentence.split(word);
console.log(splitted[0], splitted[1], etc...);
In this case if you split by John it will look exactly like you want.

How can I replace single digit numbers within a string without affecting 2 digit numbers in that string

I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>

Replace a string word with empty space with js

I have the following string:
var string = "Deluxe 3 Bed Private"
and the following code to replace the "Private" word with an empty space:
var rooms = ["Basic", "Standard", "Superior", "Deluxe", "Private"];
//var room = "room";
vwo_$(document).ready(function(){
WRI.eventBus.on('ui:microsite:availabilityStore:refresh', function(){
var roomName = $(".roomnamelink");
roomName.each(function(){
for (var i = 0; i < rooms.length; i++) {
var pattern = "[^\s]" + rooms[i];
var regex = new RegExp(pattern);
string = string .replace(regex, " ");
}
});
})
but my regex is probably wrong.
If the word "Private" is found in the string I want that replaced with an empty space.
var string = "Deluxe 3 Bed"
I want to replace any of the words found in the rooms array with an empty space
you can use one regex for all the possible words
var regex = /\b(Basic|Standard|Superior|Deluxe|Private)\b/gi
and the use it with String#replace method
var string = "Deluxe 3 Bed Private"
string.replace(regex, '')
You could search for white space and the word, you want to replace.
var re = /[\s]*?private/gi,
str = 'Deluxe 3 Bed Private',
subst = '';
var result = str.replace(re, subst);
console.log('#' + result + '#');
you can do it by using very simple code like below:
var string = "Deluxe 3 Bed Private"
//checking whether private is in String or not.
if (wordInString(string, 'Private'))
{
string = string.replace('Private', ' ');
}
alert(string);
function wordInString(s, word) {
return new RegExp('\\b' + word + '\\b', 'i').test(s);
}
that's all.. :)

How to cut third symbol from string and alert it without third symbol

How can i correctly cut out letter "v" and alert str without "v"
var str = "Javascript";
var cut = str.substring(2,3);
var str = "Javascript";
var cut = str.substring(0,2) + str.substring(3);
alert(cut);
You're using the right tool (String#substring). You need two substrings that you put back together, the "Ja" and the "ascript". So:
var str = "Javascript";
var cut = str.substring(0, 2) + str.substring(3);
alert(cut);
Another option would be String#replace, which will replace the first occurrence of what you give it unless you tell it to do it globally with a regex and the g flag (which we won't, because we just want to remove that one v):
var str = "Javascript";
var cut = str.replace("v", "");
alert(cut);
Just for fun, there is another way, but it's a bit silly: You can split the string into an array of single-character strings, remove the third entry from the array, and then join it back together:
var str = "Javascript";
var cut = str.split("").filter(function(_, index) {
return index != 2;
}).join("");
alert(cut);
or
var str = "Javascript";
var cut = str.split("");
cut.splice(2, 1); // Delete 1 entry at index 2
cut = cut.join("");
alert(cut);
...but again, that's a bit silly. :-)
use replace method
var str = "Javascript";
str = str.replace("v", "");
alert(str);

Regex to with a starting letter AND it contains a word

var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str2 = "I dont have any two";
for these string need to find a reg like it should match string starts with "I" AND contains "one" or "two".
var regx = "/^I/"; //this starts with I
var regx = "/(one|two)/"; //this match one or two
But how to combain both with an AND ?
So str1.test(regx) should be false.
Just match any character between I and one
var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str3 = "I dont have any two";
var regx = /^I.*(one|two)/
console.log(regx.test(str)) // True
console.log(regx.test(str1)) // False
console.log(regx.test(str2)) // False
console.log(regx.test(str3)) // True
Here a fiddle to test
different approach ...
var regx1 = /^I/; //this starts with I
var regx2 = /(one|two)/; //this match one or two
// starts with "I" AND contains "one" or "two".
var match = regx1.test(str1) && regx2.test(str1)
It would be better if you add a word boundary.
var regx = /^I.*? (?:one|two)( |\b).*$/;
DEMO

Categories