This question already has answers here:
What is the JavaScript string newline character?
(15 answers)
Closed 6 months ago.
I want to send a whatsapp message using this code below, but I don't know how to add line breaks in the message. I tried using \n but it still appears as 1 line.
the function
export function sendWhatsApp(phone='', msg='') {
let phoneWithCountryCode = `62${ltrim(phone, '0')}`; // 628123456789
let mobile = `+${phoneWithCountryCode}`;
let url = `whatsapp://send?phone=${mobile}&text=${msg}`;
Linking.openURL(url).then((data) => {
console.log('WhatsApp Opened');
}).catch(() => {
alert('Please make sure WhatsApp installed on your device');
});
}
// end export function sendWhatsApp
how I call the function
let msg = `Hello \n
This is first line of message \n
this is the second line`
;
sendWhatsApp('8123456789', msg);
Use "\r\n", it will work.
Related
This question already has answers here:
Encode URL in JavaScript
(22 answers)
Closed 13 days ago.
so I'm hoping someone can help. I have a text field on my page which is pulling a variable in from Active Campaign which is the company name, and turning it into a URL on my page:
https://www.vitaldocuments.co.uk/referral-link/?company=%COMPANY%
However, as you can see the variable being pulled in will have spaces in, which is fine in that it's a workable link if they copy and past it, as it will automatically add in %20 into the spaces, but I want these to be added within the text box itself so it shows it as the actual URL here. Is this possible?
Here's the code I'm using:
<script>
document.querySelectorAll(".copy-link").forEach((copyLinkParent) => {
const inputField = copyLinkParent.querySelector(".copy-link-input");
const copyButton = copyLinkParent.querySelector(".copy-link-button");
const text = inputField.value;
inputField.addEventListener("focus", () => inputField.select());
copyButton.addEventListener("click", () => {
inputField.select();
navigator.clipboard.writeText(text);
inputField.value = "Copied!";
setTimeout(() => (inputField.value = text), 2000);
});
});
</script>
-->
I've tried the script as is, but it hasn't worked out right.
I believe You can simply use the encodeURI()
method and apply it to the string of your text field
DOM values don't react try this:
document.querySelectorAll(".copy-link").forEach((copyLinkParent) => {
const inputField = copyLinkParent.querySelector(".copy-link-input");
const copyButton = copyLinkParent.querySelector(".copy-link-button");
- const text = inputField.value;
inputField.addEventListener("focus", () => inputField.select());
copyButton.addEventListener("click", () => {
+ const text = inputField.value;
inputField.select();
navigator.clipboard.writeText(text);
inputField.value = "Copied!";
setTimeout(() => (inputField.value = text), 2000);
});
});
Note: i'm pretty sure the copy button won't work on mobile you need a different code but that's beyond the scope of this question
This question already has answers here:
Rendering raw html with reactjs
(13 answers)
Closed 1 year ago.
I have a text input. I want the line breaks that the user creates to be included in the output text.
When the user clicks preview, the input value is stored in state as a string. I use .replace() to replace the line breaks with br, but the tags are visible in the output html.
DesPreviewRender = () => {
const desStateCopyOutput = this.state.inputValues.desValue.replace(/(?:\r\n|\r|\n)/g, ' <br> ');
return (
<FadeIn>
<div className="desPreview--Temp">
<p className="desPreviewValueText--Temp">
{desStateCopyOutput}
</p>
</div>
</FadeIn>
)
}
Here's a screenshot of the output:
Screenshot of html output
Thanks!
You could do the following (maybe not the best way, but it works):
generateOutput = input => {
const lines = input.split('\n')
const output = []
lines.forEach((d, i) => {
if (i > 0) {
output.push(<br/>)
}
output.push(d)
})
return output
}
As SuperDJ said, I can use dangerouslySetInnerHTML to do this. Thanks!
This question already has answers here:
Replace nth occurence of number in string with javascript [duplicate]
(2 answers)
Closed 3 years ago.
I have a code that replaces in a file all line breaks and sustitute for comma.
var fs = require('fs');
var str = fs.readFile('output.txt', 'utf-8', function(err, data) {
if (err) throw err;
console.log(data.replace(/\r\n/g, ','));
});
I'm trying to make a version that every 3 executions add a line break.
How I can accomplish this?
data.replace(/\n/g, ",").replace(/(([^,]*,){2}[^,]*),/g, '$1\n')
Or
data.replace(/\r\n/g, ",").replace(/(([^,]*,){2}[^,]*),/g, '$1\r\n')
String.prototype.replace can accept a replacer function as second argument, docs here. Using a function fits your case perfectly.
You can create a function that keeps an execution counter in its closure, then conditionally yields a line break on every 3 replacements.
function ReplacerFactory() {
var execCount = 0;
function replacer() {
execCount++;
if (execCount % 3) return ',';
return '\n';
}
return replacer;
}
console.log(data.replace(/\r\n/g, ReplacerFactory()));
var data = `a
quick
brown
fox
jumps
over
a
lazy
dog
yo!
`;
function ReplacerFactory() {
var execCount = 0;
function replacer() {
execCount++;
if (execCount % 3) return ',';
return '\n';
}
return replacer;
}
console.log(data.replace(/\n/g, ReplacerFactory()));
This question already has an answer here:
carriage return in textarea retrieved as line feed
(1 answer)
Closed 3 years ago.
If I set the value of a textarea to let's say "123456\r123" and call document.getElementById('myTextarea').value.indexOf("\n"), it returns 6, which is the position of the line break; but why is it not returning -1, as there is no \n inside the string?
I guess the browser auto transfer the '\r' to '\n' when you set value to the textarea.
When I run those codes in browser,the result told me what I guess is just the truth.
let textArea = document.getElementById("inputTextarea");
let value = "abcd\radc";
textArea.value = value;
let out = document.getElementById("outputPre");
document.getElementById("inputTextarea").addEventListener("click", () => {
value = textArea.value;
let chars = value.split("").map(s => s.charCodeAt(0));
let lf = ["\r".charCodeAt(0), "\n".charCodeAt(0)];
out.innerHTML = 'valueChars:<em>' + value.split("") + "</em><br/>ASCII:<em>" + chars.toString() + "</em>";
/*valueChars:a,b,c,d,
,a,d,c ASCII:97,98,99,100,10,97,100,99*/
console.info(lf); //13,10
});
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
var jtj_code_lines = []; // this array will hold all the jtj codes line
var JTJ = function(j){
j = j.replace(" ","");
jtj_code_lines = j.split(';'); // splitting all the lines seperated from ;
for(var i=0; i<jtj_code_lines.length; i++){
if(jtj_code_lines[i].charAt(0) === '*'){ // * means that the following word is the name of a method that will perform some action
var q1 = jtj_code_lines[i].replace('*', ''),
q1_pos_1 = q1.indexOf('['); // find the position of the keyword [
var q1_funcname = q1.slice(0, q1_pos_1); // it find the name of that perticular function
if(q1_funcname === "Message"){ // this checks weather the function name is message
var q1_pos_2 = q1.indexOf(']'), // this ifnds the position of keyword ]
q1_func_value = q1.slice(q1_pos_1+1, q1_pos_2); // this finds what is written inside [] and accepts as the value of Message
alert(q1_func_value);
}else{
}
}
}
};
so the above function is pretty simple it finds the specific text written in the braces, i mean that if you write :
JTJ('*Message[hi];')
then it will alert hi and this is quit simple and this is alerting as expected but the problem is coming that if any * is after white space then that perticular thing is not being alerted, so the following have the same condition,*Message[go ]; starts with whitespace so it is not being alerted :
JTJ('*Message[sanmveg];*Message[saini]; *Message[go ];')
but i have a this line j = j.replace(" ",""); to remove all the white spaces, then why it is not working? is there any other way to do this?
thanks.
Fix: j = j.replace(/\s/gi,"");
this would remove all " " with "", in short it would act as replaceAll.
Before it was just replacing first matched " " with "".