I have a string like hey! <input/>, Welcome in a template.
I need to replace every <input/> with the a JS expression this.input.
eg:
//Input
"hey! <input/>, Welcome";
Output should be:
"hey! " + this.input + ", Welcome";
I can do a replace on the string with " + this.input + " but the problem is what if <input/> at the start or the end?
What is the best way to handle this?
Edit:
I don't want the output to be a string. I want the output to be a valid JS expression.
Valid inputs:
1) "hey! <input/>, Welcome";
2) "<input/>, Welcome";
3) "Welcome <input/>"
Outputs:
1) "hey! " + this.input + ", Welcome";
2) this.input + ", Welcome";
3) "Welcome " + this.input;
As I wrote in comments above you can use:
var input = 'foo';
var str = "hey! <input/>, Welcome";
str = str.replace(/(.*?)<input\/>(.*)/, '$1' + this.input + '$2');
console.log(str);
//=> "hey! foo, Welcome"
"hey! <input/>, Welcome".replace(/<input\/>/, this.input);
EDIT:
John Reisig made a blog entry about making a minimal templating language parser in javascript. It's well written and may be a good starting point for your own templating language.
Related
I'm struggling with an Regex to replace the name of a variable inside a string...
I need to put certain variable name outside quotes, and, if that variable have a qualifier (like a property or method), this qualifier need to be outside quotes in the final string, too.
So, given this example:
cExp = new RegExp('oErro', 'g');
cMsg = "Error ocurred: oErro; please try again";
cMsg.replace(cExp, '\' + oErro + \'')
the output is exactly what I expect:
'Error ocurred: ' + oErro + '; please try again'
I search how to include any words after the variable name, and ended up with this piece of code:
cExp = new RegExp('oErro(\.[^\ |^\;|^\,|^\)|^\}]*)', 'g');
cMsg = "Error ocurred: oErro.message; please try again";
cMsg.replace(cExp, '\' + oErro$1 + \'')
and the result is exactly what I expected to see:
'Error ocurred: ' + oErro.message + '; please try again'
So far, so good.
But, if I mix variable name with variable.qualifier, things start to get messy:
cExp = new RegExp('oErro(\.[^\ |^\;|^\,|^\)|^\}]*)', 'g');
cMsg = "Error ocurred: oErro.message (complete message: oErro)";
cMsg.replace(cExp, '\' + oErro$1 + \'')
I GET this output
'Error ocurred: ' + oErro.message + ' (complete message: ' + oErro) + ''
while I EXPECTED this output (note the parenthesis INSIDE the quotes)
'Error ocurred: ' + oErro.message + ' (complete message: ' + oErro + ')'
In other words, every time "oErro" is used without a qualifier, the expression gets the next word and join with oErro, outside the enclosing quotes.
Certainly I'm doing something wrong, but I'm not very familiar with RegExp and maybe not searching with correct terms to get appropriate help.
What I need is an expression that works for both scenarios (removing the word "oErro" or the syntax "oErro.something" from quotes in the final string)...
Thanks in advance and sorry for the poor english, I try to put some examples but feel free to ask if you need more details on what I need to achieve.
You may use
cExp=/oErro(?:\.[^\s;,)}]+)?/g
// Or, if the chars after `.` can only only be letters/digits/underscore
cExp = /oErro(?:\.\w+)?/g
Then, you would need to use
cMsg.replace(cExp, '\' + $& + \'')
where $& is the backreference to the whole match value.
Pattern details
oErro - a literal string
(?:\.\w+)? - an optional (due to ? at the end) non-capturing group that matches 1 or 0 occurrences of
\. - a dot
-\w+ - 1+ letters/digits/underscores
[^\s;,)}]+ - 1 or more chars other than whitespace, ;, ,, ) and }.
I believe your requirement for capturing the property or method name is satisfied by using the \w character in your regex.
With oErro
cMsg = "Error ocurred: oErro; please try again";
cMsg.replace(/(oErro(\.\w+)?)/g, '\' + $1 + \'');
// Output: "Error ocurred: ' + oErro + '; please try again"
With oError.message
cMsg = "Error ocurred: oErro.message (complete message: oErro)";
cMsg.replace(/(oErro(\.\w+)?)/g, '\' + $1 + \'');
// Output: "Error ocurred: ' + oErro.message + ' (complete message: ' + oErro + ')"
I'm just beginning my learning process and am stuck now on this one string. I've searched MDN, Google and Bing and not found any help.
My code instructions tell me to assign a variable, which I did. Then it wants me to test in console.log. I've done so, and when I do with spaces and punctuation, it gives me an error saying that it expected an identifier and instead saw '+'.
If I take the punctuation out I don't have an error, but no punctuation. If I take out the extra spaces as well as punctuation, I get a strange run-on sentence but no errors. I'm working this problem in Udacity, it is quiz 24 of lesson 2.
My code is:
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1. + " James and Julia are so " + adjective2. + " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
You need to add the dots as strings as well.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + "."
+ " James and Julia are so " + adjective2 + "."
+ " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
The dot . has a special meaning in Javascript. It works as accessor for properties of an object.
Math.floor(1.5); // return the integer value of the given number
Read more here about property accessor.
Add . (dot) inside the double quoted part of string, not next to the variable.
It is a part of string, not a in-memory variable. And you are calling no function after that.
Below snippet works properly.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + ". James and Julia are so " + adjective2 + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
Example of using dot to call a function. It is not required in this case since it is already a string.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1.toString() + ". James and Julia are so " + adjective2.toString() + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
I have the following string:
var myString = "Name: ";
function replaceName(str, name) {
return str.replace(/Name:/gi, "Name:" + name);
}
myString = replaceName("Name: ", "Joe");
myString = replaceName("Name: ", "Jane");
I want to replace the entire line each time a new name is added. The above keeps appending the name to the end of the string.
How can I replace the name each time str.replace is called?
Firstly, you could have mentioned clearly that calling the function second time messes up. And secondly, there's no functions in your code, so you need to tell which line is messing up. I understood the question with the help of Rory McCrossan and here's the answer.
I changed the code and using this RegEx worked:
var str = "Name: ";
str = str.replace(/Name:.*/gi, "Name:" + "Joe");
console.log(str);
str = str.replace(/Name:.*/gi, "Name:" + "Prav");
console.log(str);
Explanation for the RegEx
psst: There's no better explanation than RegEx101...
I want to encode a string to UTF-8 in JavaScript. In java we use URLEncoder.encode("String", "UTF-8") to achieve this.
I know we can use encodeURI or encodeURIComponent but it is producing different output than URLEncoder.encode
Can anyone please suggest any available JS method that can be used to achieve same output as URLEncoder.encode.
NOTE:
Due to restrictions I cannot use jQuery.
I don't know if this javaURLEncode() function is a spot-on match for Java's URLEncoder.encode method, but it might be close to what you're looking for:
function javaURLEncode(str) {
return encodeURI(str)
.replace(/%20/g, "+")
.replace(/!/g, "%21")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/~/g, "%7E");
}
var testString = "It's ~ (crazy)!";
var jsEscape = escape(testString);
var jsEncodeURI = encodeURI(testString);
var jsEncodeURIComponent = encodeURIComponent(testString);
var javaURLEncoder = javaURLEncode(testString);
alert("Original: " + testString + "\n" +
"JS escape: " + jsEscape + "\n" +
"JS encodeURI: " + jsEncodeURI + "\n" +
"JS encodeURIComponent: " + jsEncodeURIComponent + "\n" +
"Java URLEncoder.encode: " + javaURLEncoder);
found one more character should be replaced
.replace(/\$/g, "%24")
string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])
For some reason, this isn't affecting both the filter followed by the space and the filter with a space in front. Assuming the filter is ",", it would take the second side and only replace " ," rather than " ," and ", ". The filter is user-specified, so I can't use a normal regular expression (which DOES work) such as string=string.replace(/, | ,/g,filter[a])
Can someone explain to me why it doesn't work and how to make it work?
It works for me:
s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"
Remember that you regular expression won't replace " , " with ",". You could try using this instead:
" ?" + filter[a] + " ?"