This question already has answers here:
JavaScript equivalent to printf/String.Format
(59 answers)
Javascript multiple replace [duplicate]
Closed 9 years ago.
Lets say I have the following string in my javascript code:
var myText = 'Hello %1. How are you %2?';
Now I would like to inject something in place of %1 and %2 in the above string. I can do:
var result = myText.replace('%1', 'John').replace('%2', 'today');
I wonder if there is a better way of doing than calling 2 times the replace function.
Thanks.
How about a little format helper? That's basically what you need:
function format(str, arr) {
return str.replace(/%(\d+)/g, function(_,m) {
return arr[--m];
});
}
var myText = 'Hello %1. How are you %2?';
var values = ['John','today'];
var result = format(myText, values);
console.log(result); //=> "Hello John. How are you today?"
Demo: http://jsbin.com/uzowuw/1/edit
Try this sample
function setCharAt(str,chr,rep) {
var index = -1;
index= str.indexOf(chr);
var len= chr.length;
if(index > str.length-1) return str;
return str.substr(0,index) + rep + str.substr(index+len);
}
var myText = 'Hello %1. How are you %2?';
var result = setCharAt(myText,"%1","John");
var result = setCharAt(result,"%2","today");
alert(result);
This is meant just as a complex comment to elclarns' great answer, suggesting these alternatives:
Can be written as String.prototype
Can use arguments
The function can be altered to
String.prototype.format = function() {
var args=arguments;
return this.replace(/%(\d+)/g, function(_,m) {
return args[--m];
});
}
And called this way
var result = "I am %1, %2 years old %1".format("Jan",32);
// I am Jan, 32 years old Jan
Related
This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));
This question already has answers here:
Split string once in javascript?
(17 answers)
Closed 8 years ago.
I know there are several ways to split an array in jQuery but I have a special case:
If I have for example this two strings:
"G09.4 What"
"A04.3 A new Code"
When I split the first by ' ' I can simply choose the code in front with [0] what would be G09.4. And when I call [1] I get the text: What
But when I do the same with the second string I get for [1] A but I want to retrieve A new Code.
So how can I retrieve for each string the code and the separate text?
Use
var someString = "A04.3 A new Code";
var index = someString.indexOf(" "); // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1); // Gets the text part
You can split the string and shift off the first entry in the returned array. Then join the leftovers e.g.
var chunks = "A04.3 A new Code".split(/\s+/);
var arr = [chunks.shift(), chunks.join(' ')];
// arr[0] = "A04.3"
// arr[1] = "A new Code"
Instead of splitting the string on the space, use a combination of indexOf and slice:
var s = "A04.3 A new Code";
var i = s.indexOf(' ');
var partOne = s.slice(0, i).trim();
var partTwo = s.slice(i + 1, s.length).trim();
You can use match() and capture what you need via a regular expression:
"G09.4 What".match(/^(\S+)\s+(.+)/)
// => ["G09.4 What", "G09.4", "What"]
"A04.3 A new Code".match(/^(\S+)\s+(.+)/)
// => ["A04.3 A new Code", "A04.3", "A new Code"]
As you can see the two items you want are in [1] and [2] of the returned arrays.
What about this one:
function split2(str, delim) {
var parts=str.split(delim);
return [parts[0], parts.splice(1,parts.length).join(delim)];
}
FIDDLE
Or for more performance, try this:
function split2s(str, delim) {
var p=str.indexOf(delim);
if (p !== -1) {
return [str.substring(0,p), str.substring(p+1)];
} else {
return [str];
}
}
You can get the code and then remove it from the original string leaving you with both the code and the string without the code.
var originalString = "A04.3 A new Code",
stringArray = originalString.split(' '),
code,
newString;
code = stringArray[0];
newString = originalString.replace(code, '');
This question already has answers here:
JavaScript reverse the order of letters for each word in a string
(5 answers)
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 9 years ago.
Was wondering if you can reverse a string and still maintain the order.
Below is a function that returns "dlroW olleH" and I want to return "olleH dlroW"
var myFunction = function() {
var userdata = document.getElementById('data').value,
uRev = userdata.split("").reverse().join("");
document.getElementById('results').innerHTML = uRev;
};
Thanks!
Reverse the words and then the characters:
var myFunction = function() {
var userdata = document.getElementById('data').value,
uRev = userdata.split(" ").reverse().join(" ").split("").reverse().join("");
document.getElementById('results').innerHTML = uRev;
};
Example JSFiddle
function reverseString(s){
return s.split("").reverse().join("");
}
function reverseEachWord(s) {
return s.split(" ").map(reverseString).join(" ");
alert(userdata.split(" ").reverse().join(" ").split("").reverse().join(""));
first split your string in an array of words using split(" "), then split each array segment using the method above.
Try this,
var myFunction = function() {
var resArr=[];
var userdata = document.getElementById('data').value,
uRev = userdata.split("");
for (var i=0;i<uRev.length;i++){
resArr.push(uRev[i].reverse());
}
document.getElementById('results').innerHTML = resArr.join('');
};
var test = 'Hello World';
alert(
test.replace(
/\w+/g ,
function(a){return a.split('').reverse().join('');}
)
);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Possible to assign to multiple variables from an array?
If in python i can do this
x = "Hi there and hello there"
v1, v2, v3, v4, v5 = x.split(" ")
but im not sure how to do it in javascript..
You can turn it into an array by using javascript .split
For example
x = "Hi there and hello there";
var array = x.split(" ");
Then all your variables will be in the array like below
array[0]
array[1]
array[2]
You can show this using console.log or an alert like so.
console.log(array[0]);
alert(array[0]);
References
http://www.tizag.com/javascriptT/javascript-string-split.php
What you are asking is called "destructuring assignment" which is a feature of Javascript 1.7. Sadly, not all browsers support these JS 1.7 features (Chrome for example, executes code marked as JS 1.7 but does not yet support this feature).
Your code will work on Firefox (as long as you mark it as JS 1.7 and with a slight modification) but not on Chrome.
To see this in action, use the following with Firefox:
<script type="application/javascript;version=1.7"/>
x = "Hi there and hello there"
var [v1, v2, v3, v4, v5] = x.split(" ")
</script>
split splits the string into an array of strings.
Split returns an array.
var x = "Hi there and hello there"
var v = x.split(" ")
console.log(v[0]);
console.log(v[1]);
if you can attach the variables to an object, then you could do it this way:
var stringToWords = function (str) {
if (typeof str === "string") {
var stringsArray = str.split(" "),
stringsSet = {};
for (var i = 0, wordsNumber = stringsArray.length; i < wordsNumber; i++) {
stringsSet['str' + (i + 1)] = stringsArray[i];
}
return stringsSet;
} else {
return str + " is not a string!!!"}
};
// this will return an object with required strings
var allStringWords = stringToWords("Hi there and hello there");
//then you can access a word this way:
allStringWords.str1
but I'm sure there are shorter ways to gain the same
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I am using below code to replace , with \n\t
ss.replace(',','\n\t')
and i want to replace all the coma in string with \n so add this ss.replaceAll(',','\n\t') it din't work..........!
any idea how to get over........?
thank you.
You need to do a global replace. Unfortunately, you can't do this cross-browser with a string argument: you need a regex instead:
ss.replace(/,/g, '\n\t');
The g modifer makes the search global.
You need to use regexp here. Please try following
ss.replace(/,/g,â\n\tâ)
g means replace it globally.
Here's another implementation of replaceAll.
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Then you can use it like:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");