I have a confirmation pop-up dialog in which I am passing a variable which is a comma separated string.
How can I replace the commas and introduce a line break?
I tried using replace. I tried passing '\n' separated list from back-end. But nothing seems to work — though a normal confirm() used for testing purposes is working fine.
var listcontrol = document.getElementById(id3);
var List = listcontrol.innerText;
var finallist = List.replace("\n", "\n");
if (checkboxCell.checked == false) {
if (labelCell.innerText == "Yes") {
confirm("The selected exam is present in the following certifications: " + "\n" + finallist + "\n" +
"Uplanning this exam here would unplan the same exam under other certification(s) also.");
}
}
In your code you are replacing "\n" with "\n", which would make no difference. You want to replace "," with "\n" instead, right?
var string = "Demetrius Navarro,Tony Plana,Samuel L. Jackson";
alert(string);
alert(string.replace(/,/g, "\n"));
Live test - http://jsfiddle.net/9eZS9/
Js replace is,
string.replace(searchvalue,newvalue)
var finallist = List.replace(/,/g, "\n");
If your "pop-up dialog" is a custom html/css-based dialog then newline characters would be treated (more or less) the same as space characters. You'd need to use <br> elements instead, so:
var finallist = List.replace(/,/g, "<br>");
Note the use of the regex as the first argument for replace() - this is needed in order to do a global replace.
For use in a standard confirm you'd need newline characters like you were doing, but with a regex rather than a string for the replace() search term:
var finallist = List.replace(/,/g, "\n");
Related
For example
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "") //Thisismystring
Now that all the whitespaces have been removed, how do I put them back in the exact position?
Additionally, let's suppose the replaced string undergoes some change and becomes
let myChangedString = "(T)(h)(i)(s)(i)(s)(m)(y)(s)(t)(r)(i)(n)(g)";
Now I want to put the whitespaces back where they used to be i.e after (s) and before (i), after (s) and before (m), after (y) before (s)
I've spent a couple of hours on this and been stuck in the same position, any form of help would be greatly appreciated.
EDIT: Solved, thank you very much.
The trick here is to replace the spaces with another character - rather than just removing the space. That way - its a simple matter to replace the added character with a space to return the spaces to where they started. When I do this - I always use the tilde character "~" since it is easily recognisable as well as unlikely to actually be used in a string.
I have added a few variations / modifications as well as the example you have provided with every character being wrapped in parentheses - just note that you will need to escape these when replaceing the (~) for the " " space character.
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "~");
console.log(replacedString);//This~is~my~string
let modifiedString = replacedString.replace(/my/g, "your");
console.log(modifiedString);//This~is~your~string
let spacedString = modifiedString.replace(/~/g, " ");
console.log(spacedString);//This is your string
// using your example of wrapping each character in parentheses
let myChangedString = "(" + modifiedString.split('').join(")(") + ")";
console.log(myChangedString); //(T)(h)(i)(s)(~)(i)(s)(~)(y)(o)(u)(r)(~)(s)(t)(r)(i)(n)(g)
let mySpacedString = myChangedString.replace(/\(~\)/g, " ");
console.log(mySpacedString); //(T)(h)(i)(s) (i)(s) (y)(o)(u)(r) (s)(t)(r)(i)(n)(g)
Why not replace only the parts you need to be replaced?
For example search for word character and replace with the wanted parts.
console.log("This is my string".replace(/\w/g, '($&)'));
Better you just transform your original array. Loop through array and modify the char is not empty.
let myString = "This is my string";
let chars = [...myString].map(item => item !== ' ' ? '(' + item + ')': item)
console.log(chars.join(''))
Are you looking for this...
var result = "thisismystring".replace(/^(.{4})(.{2})(.{2})(.*)$/, "$1 $2 $3 $4");
alert(result);
Hi I have a text something like
"Welcome back ##Firstname ##Lastname. You Last accessed on ##Date"
My objective is to replace these tokens with actual values.
So what i did was
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;
var data = str.split('#');
My idea was - once i do this, my data will have an array of values something like
["Welcome back", "#FirstName" , "#LastName", "You Last accessed on" , "#Date"]
Once i have this, i can easily replace the tokens because i will know which one are properties and which one are static string. But fool i am since JS has other ideas.
it instead split it as :
["Welcome back ", "", "Firstname ", "", "Lastname. You Last accessed on ", "", "Date"]
What am i doing wrong? or what is the best way to replace tokens in a string?
I looked here. Did not like the approach much. Not a fan of curly brackets. would like to do it the "#" way - Since it will be easy for Content authors
Another regex option, split on /#(#\w+)[^\w#]+/, captures the name part while throwing off the first #, assuming the name identifiers are always made up of word characters:
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;"
var data = str.split(/#(#\w+)[^\w#]+/);
console.log(data.filter(s => s !== ""));
You can split "#" characters which are followed by "#" characters
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var res = str.split(/#(?=#)/);
console.log(res);
you can replace the '##' by some character followed by '#' like ',#' and then replace on that new character.
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var data = str.replace(/##/g, ',#').split(',');
console.log(data);
As your delemiters end with a space, may split by space:
.split(" ")
And then iterate and replace all words beginning with ##
var replaceBy={
lastname:"Doe",
name:"John"
}
var result= input.split(" ").map(function(word){
if(word[0]=="#" && word[1]=="#"){
return replaceBy[word.substr(2)] || "error";
}
return word:
}).join(" ");
However, it might be easier to suround your identifiers with delemiters e.g.:
Hi ##lastname##!
So you can do
.split("##")
And every second element is automatically an identifier.
Do this:
data = str.replace("##Firstname", "Robert").replace("##Lastname","Polson").replace('##Date','yesterday') ;
I have the following string of text:
textString1:textString2:textString3:textString4
I'm looking to capture each text string and assign them to variables.
I've somehow managed to come up with the following:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var subString, intro, host, priority, queue = '';
var re = /(.+?\:)/g;
subString = errorText.match(re);
intro = subString[0];
host = subString[1];
priority = subString[2];
//queue = subString[3];
console.log(intro + " " + host + " " + priority);
JS Bin Link
However, I'm having problems with:
capturing the last group, since there is no : at the end
the variables contain : which I'd like to strip
You don't need a regex for this - just use errorText.split(':') to split by a colon. It will return an array.
And if you then want to add them together with spaces, you could do a simple replace instead: errorText.replace(/:/g,' ').
use split method for this.it will return array of string then iterate through array to get string:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var strArr=errorText.split(':');
console.log(errorText.split(':'));
for(key in strArr){
console.log(strArr[key]);
}
for example:
var a = "1234";
var b = "line1\\\\.5";
now this line of code:
"#" + a + b;
puts out this string
"#1234line1\\.5"
and when I enter it in the selector like this:
$("#1234line1\\.5")
it shows the correct element
but $("#" + a + b)
Does not
Thanks in advance for any suggestions
I'm surprised it works in the console, the id selector is invalid. CSS id selectors cannot start with a digit. You can escape it, though:
var a = "\\31 234"; // \\31 = 1, then you need the space to terminate the escape
var b = "line1\\.5"; // Removed a pair of \\ from this, I assume you
// don't have a backslash in the id
$("#" + a + b).html("Found it");
This works, for instance: Live Example
<div id="1234line1.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\.5";
$("#" + a + b).html("Found it");
})();
</script>
If you really have a backslash in the id, the escape for a backslash is \5c, which you write in a string literal as \\5c, so: Live Example
<div id="1234line1\.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\5c \\.5";
$("#" + a + b).html("Found it");
})();
</script>
One thing first: Depending on the Doctype you use, IDs may not contain backslashes or start with numbers. Please check that first.
A backslash within a Javascript string indicates that the next character should be escaped. So if you want to use a backslash within your name, then you have to escape it with a leading backslash.
If you write a code like this:
$('#abc\\\\d')
then it refers to an element with the ID abc\\d (which may be illegal to use), because both of your backslashes are being escaped.
The problem is not that the id starts with a digit, Html 5 supports this kind of ids
the problem is that you put 4 backslash instead of 2
so instead of searching for
#1234line1\.5
you searched for
#1234line1\\.5
just change it to
var b = "line1\\.5";
and it will work fine
I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces".
I've used the following code but I just can't get it to work:
<html>
<body>
<script type ="text/javascript">
// Program to replace any spaces in a string of text with the word "spaces".
var str = "Visit Micro soft!";
var result = "";
For (var index = 0; index < str.length ; index = index + 1)
{
if (str.charAt(index)= " ")
{
result = result + "space";
}
else
{
result = result + (str.charAt(index));
}
}
document.write(" The answer is " + result );
</script>
</body>
</html>
For
isn't capitalized:
for
and
str.charAt(index)= " "
needs to be:
str.charAt(index) == " "
JavaScript Comparison Operators
for loops
As others have mentioned there are a few obvious errors in your code:
The control flow keyword for must be all lower-case.
The assignment operator = is different than the comparison operators == and ===.
If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function.
Another option would be to skip the for cycle altogether and use a regular expression:
"Visit Micro soft!".replace(/(\s)/g, '');
Try this:
str.replace(/(\s)/g, "spaces")
Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string Hope this help
You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop.
Example of replace:
var word = "Hello"
word = word.replace('e', 'r')
alert(word) //word = "Hrllo"
The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear.
Example:
var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1