Replace a string word with empty space with js - javascript

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.. :)

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.

regex (only 1 dot)

I have a regEx where I replace everything whats not a number:
this.value.replace(/[^0-9\.]/g,'');
how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)
(I know you can use input just number (thats not an option in this project for me))
You can use a simple trick of:
splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi
Here is an example code:
// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
Proof-of-concept example:
var tests = [
'xx99',
'99xx',
'xx99xx',
'xxxx999.99.9xxx',
'xxxx 999.99.9 xxx',
'xx99xx.xx99xx.x9',
'xx99xx.99x.9x',
'xx99.xx99.9xx'
];
for (var i = 0; i < tests.length; i++) {
var str = tests[i];
// Split and rejoin, keeping only first occurence of `.`
var splitStr = str.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}
I resolved it with.
this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");

JavaScript: Take first three characters of each word in string and put "_" after each word

What I would like to achieve is take a string:
var string = "Hello there my friend";
And return a formatted string as follows:
"HEL_THE_MY_FRI"
So I am trying to take the first three characters of each word in a string and add an underscore after each. The capitalize is easy :) .toUpperCase()
You could use replace for that:
var string = "Hello there my friend";
var result = string.toUpperCase().replace(/\b(\S{1,3})\S*/g, '$1').replace(/ /g, '_');
console.log(result);
Since you didn't provide any code for what you've tried so far, the steps you'd take are:
split the string on spaces
loop over your array of words
get a substring from each word 3 characters long
uppercase the substring
append it to your new string
add an underscore if it isn't the last word in your array
var phrase = 'this is my string';
var words = phrase.split(' ');
var result = '';
for (var i = 0; i < words.length; i++) {
var word = words[i];
result += word.substring(0, 3).toUpperCase();
if (i < words.length - 1) {
result += '_';
}
}
console.log(result);
"One-line" solution using String.replace(), String.toUpperCase() and String.slice() functions:
var string = "Hello there my friend",
replaced = string.replace(/\b(\w{1,3})(\w+\s?|\s)/g, '$1_').toUpperCase().slice(0,-1);
console.log(replaced);
console.log("Hello there my friend".split(" ").map((a)=>a.substring(0, 3)).join("_").toUpperCase());

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>

How can I replace a string by range?

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.

Categories