Treat String as JavaScript and output variables - javascript

Assume I have string '${hello} ${love} times'
I would like to replace hello by the variable named hello and love by the variable named love without removing times. I am using ReactJS with JSX.
My attempt is just removing the $, { and } from the string and then deal with it.
var cut = this.props.string.split(" ");
var one = cut[0].split("{");
var two = one[1].split("}");
var thin = this.var[two[0]];
and then use thin

Your question is completely unclear... Do you know how ES6 template literals work? You have to use backticks to enable string interpolation, not regular quotes ('' or "").
Is this what you are trying to do?
let hello = 'Hello',
love = 'LOVE';
console.log(`${hello} ${love} times`);

Related

Replace Curly Braces in string with a HTML span Node in JSX

I have a string I need to parameterise like 'Hello {name}, how are you?'. I want to replace the curly braces and text inside with a variable then render it in my React Component but I also need that text to be highlighted and bold by wrapping the variable text in a span/strong tag e.g. of desired final result
Hello <span class="text-info"><strong>Dave</strong></span>, how are you?
I'm using React/JSX and I know how to replace the curly braces and text inside them using String.replace then render it e.g.
// This string with the placeholder curly braces would be received from an API call to a server. Only set here for demonstrative purposes
let string = 'Hello {name}, how are you?'
let name = 'Dave' // Likewise would not be set manually here, it's held in a redux store
let greeting = string.replace(/{(.*?)}/, name);
// This renders the greeting as you'd expect e.g. <p>Hello Dave, how are you?</p>
return (
<p>{greeting}</p>
)
However, if I try and replace the curly braces with a span element it renders incorrectly with [object Object] instead of my parameter
// ...rest of stateless Component.jsx
let greeting = string.replace(/{(.*?)}/, <span>{name}</span>);
// This renders the HTML <p>Hello [object Object], how are you?</p>
return (
<p>{greeting}</p>
)
I think it must be something to do with React escaping something but to be honest that's a total guess. Any ideas how I can achieve the desired functionality?
JSFiddle: https://jsfiddle.net/ExoticChimp1990/o69ymt7q/
You can try replacing by a string containing raw html tags and then render your div using dangerouslySetInnerHTML.
var greeting = textToEnhance.replace(/{(.*?)}/, '<span>'+this.props.name+'</span>');
return <div dangerouslySetInnerHTML={{__html:greeting}}></div>;
BTW, you can use the formatting of ES6 e.g.
const name = "David";
const myHTML = `Hello ${name}, how are you?`;
Note: these are not single quotes, but ` symbols. This symbol called as "grave accent" character
I understand your templates come from a server, so you cannot directly use the method above.
However, using RegExp such as /\$\{(\w+?)\}/g (click to expirement with this RegExp) you can parse and iterate through all your variable names e.g.
var newString = templateString.replace(/(\$\{\w+?\})/g, function(match, p1, offset, str) {
var matches = /\$\{(\w+?)\}/.exec(p1);
var variableName = matches[1];
return variables[variableName]
?variables[variableName]
:console.error("Variable " + variableName + " is undefined in offset " + offset);
});
When variables is a predefined object containing your variables as key values pairs and templateString contains your template (optionally from a server).
The second argument you are using in string.replace is not correct. name variable inside curly braces means, a javascript object with name key and value as that in name variable.
let greeting = string.replace(/{(.*?)}/, '<span><strong>'+name+'</strong></span>');
I am sorry, as I didnt enter the string above as code, it ommited the tags. Now they must be visible.

ES6 when to use String.raw over default template literal

I'm trying to concatenate a bunch of strings to build a query string in Javascript. Previously I have achieved this through ugly string concatenation:
var queryString = "?action=" + actionValue + "&data=" + dataValue";
But with ES6 I see that there are new methods provided that could help me achieve the same result with much nicer looking code, like string interpolation in C# 6:
string s = $"action={actionValue}&data={dataValue}"
I have tested with both default template literal and String.raw and although the syntax for each is slightly different, they both work. I'm leaning towards using String.raw in my final copy as it doesn't allow for the string to be tagged and thus tinkered with in the future like the default template literal does.
Although it does say in the MDN docs that String.raw basically calls the default template literal method but I like the syntax of String.raw better... I am calling the String.join method inside the curly braces of my string that I am formatting so maybe that is a misuse of String.raw.
Are any ES6 wizards out there able to enlighten me and provide reasons for one over the other?
My code:
var defaultTemplateStringUrl = `#Url.Action("DownloadMultiple")?inIds=${inData.join(',')}&outIds=${outData.join(',')}&truckId=${truckId}`;
var rawStringUrl = String.raw `#Url.Action("DownloadMultiple")?inIds=${inData.join(',')}&outIds=${outData.join(',')}&truckId=${truckId}`;
window.open( /*url goes here*/);
A template literal produces a string. If you use String.raw, you will get the raw form of that string:
`a\tb`; // "a b"
String.raw`a\tb`; // "a\tb"
So you should use String.raw only when you want the raw form.
No, using String.raw makes no sense for you.
You should rather write your own template tag that does the necessary URL encoding and handles arrays in a manner you like.
function myUrl(parts) {
var url = parts[0];
for (var i=1; i<arguments.length; i++) {
var val = arguments[i];
if (Array.isArray(val))
val = val.join(",");
url += encodeURIComponent(val);
url += parts[i];
}
return url;
}
Then you can use
window.open(myUrl`#Url.Action("DownloadMultiple")?inIds=${inData}&outIds=${outData}&truckId=${truckId}`);

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

How do I write if ''not'' in Javascript

I have this code :
el("inp").onpropertychange=function(){
addScript("http://www.google.nl/complete/search?callback=suggest&q="+this.value);
};
I want to exclude the arrow keys. As I understand I can do this with if (!(condition)) {action} But how do I write this in the code above?
If I'm understanding you correctly you can simply replace the angle brackets in the this.value string with an empty string.
var query = this.value.replace(">","").replace("<","");

how to define dynamic variable in javascript

when i define in javascript
var whoami = #ViewBag.myname
it is not work or render they render
var whoami = ;
i am trying it #(ViewBag.myname) // not worked too.
are their any way to do this in raor MVC 3
Is #ViewBag.myname empty?
Enclose the variable in quotes, so to have a correct javascript string:
var whoami = "#ViewBag.myname";
also ensure that myname doesn't contain quotes too (or escape them).

Categories

Resources