How can I get the word in between quotation marks and then replace it with something else from reading from a file
Note: I know how to read and write from files, I just need to know about getting the word from inside quotation marks
If you know the word you're looking for:
let text = 'Sentence with "word" in it';
let wordFromFile = "nothing";
let newText = text.replace('"word"', wordFromFile);
Or else regular expression is useful.
Using Regex(regular expression) with regex replace :
let str = 'How can I get the word in between "quotation marks"';
let word = str.replace(/.*"(.*?)".*/g,'$1');
let replacedWord = 'single quotes';
console.log(str.replace(word,replacedWord))
You can find the word with a quotation mark for example word by /"[^"]+"/ and replace it with other words for example key
const str = 'This is the "word" which inside two quotation marks'
const result = str.replace(/"[^"]+"/g, 'key')
console.log(result)
Related
I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?
Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);
You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo
const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());
I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...
I am new to javascript currently working on discord bots
I coded a bot which responds to messages but when I give input in capital letters or by giving space the bot not responding please help me to fix this
This is my code and if I give input like "Hi bro"
It doesn't respond
bot.on("message", async message => {
if(message.author.bot || message.channel.type == 'dm') return;
let prefix = "-";
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if(cmd === `${prefix}hibro`) {
return message.reply("Hi bro!")
}
)}
Mostly your solution is to bring to the same format either making lowercase all the letters or capital. It's up to you, but better lowercase. Also you can use trim() to avoid multiple spaces.
const str = 'Whatever Text You Want';
const res = str.replace(/\s+/g,'').toLowerCase();
console.log(res)
Compare after making string lowercase. Example
var str = "Hello World!";
var res = str.toLowerCase();
If you want to convert all the letters to the small case then Javascript has toLowerCase() method available for strings. To replace the whitespace you can use the replace method.
So the following code will give the output: hibro!
"Hi bro!".toLowerCase().replace(/\s/g,'')
/\s/g finds all the occurrences of white space in the strings.
May be you can try the below,
const str1 = 'Whatever Text You Want';
var k=[...str1.toLocaleLowerCase()];
var s='';
k.forEach(temp=>{
s+=(temp!=' ')?temp:''
})
a.trim() only removes the trailing spaces at the end and the beginning of the string, it won't capture in between spaces.
May be you can refer about String.prototype.trim() MDN docs here
this shall do the trick.
if you get the message using message.content than replace all of the spaces with dashes using replaceAll and conver it to lower case with .toLowerCase()
message.content.replaceAll(' ', '-').toLowerCase()
I have a word like this What’s On. How to remove space and ’?
I can remove space like so data.caption.replace(/ +/g, "") How to do the other part?
You can use [] to provide a character set. So in this case, the following would match against the weird quote and a space.
/[’ ]+/g
This expresion might simply work:
\s*’
which checks for 0 or more spaces prior to ’.
console.log("What ’s On ?".replace(/\s*’/,""));
console.log("What ’s On ?".replace(/[\s’]+/,""));
Or if we wish to replace all spaces:
const regex = /([^\s’]+)|(.+?)/gm;
const str = `What ’s On ?`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))