I have a string:
var myStr = 'This is a test';
I would like to make it comma delimited via JavaScript, like so:
var myNewStr = 'This, is, a, test';
What is the best way to accomplish this via JavaScript?
I know I can trim the commas like so:
var myStr = myNewStr.split(',');
And that would give me this:
myStr = 'This is a test';
But I am wanting to do the opposite of course, by adding commas.
You could just replace with regex - it is shorter and no need to split.
var myNewStr = myStr.replace(/ /g,', ');
In case you could also face the string with leading / trailing spaces, just trim it beforehand.
var myNewStr = myStr.trim().replace(/ /g,', ');
Try this - var myNewStr = myStr.split(' ').join(', ')
You could use a regular expression with a positive lookahead and replace then with a comma.
console.log('This is a test'.replace(/(?= .)/g, ','));
console.log('This is a test '.replace(/(?= .)/g, ','));
Use String.replace:
var myStr = 'This is a test';
var myNewStr=myStr.replace(/ /g,', ');
You could use the replace function to replace the spaces with commas:
var myStr = myNewStr.replace(' ', ',');
You could also use:
var myStr = myNewStr.split(' ');
Here is a way to do it without using the standard methods.
var myStr = "THIS IS A TEST";
before.innerHTML = myStr;
var parts = [];
var buffer = '';
for(var i = 0; i < myStr.length; i++) {
if(myStr[i] == ' ') {
parts.push(buffer);
buffer = '';
continue;
} else {
buffer += myStr[i];
}
}
parts.push(buffer)
var myNewStr = parts.join(', ');
after.innerHTML = myNewStr;
<div><b>Before</b></div>
<div id="before"></div>
<div><b>After</b></div>
<div id="after"></div>
The solution using String.trim and String.replace functions:
var myStr = ' This is a test ',
myNewStr = myStr.trim().replace(/([^\s]+\b)(?!$)/g, "$&,");
// $& - Inserts the matched substring.
console.log(myNewStr); // "This, is, a, test"
Related
What I would like to achieve is take a string:
var string = "Hello there my friend";
And return a formatted string as follows:
"HEL_THE_MY_FRI"
So I am trying to take the first three characters of each word in a string and add an underscore after each. The capitalize is easy :) .toUpperCase()
You could use replace for that:
var string = "Hello there my friend";
var result = string.toUpperCase().replace(/\b(\S{1,3})\S*/g, '$1').replace(/ /g, '_');
console.log(result);
Since you didn't provide any code for what you've tried so far, the steps you'd take are:
split the string on spaces
loop over your array of words
get a substring from each word 3 characters long
uppercase the substring
append it to your new string
add an underscore if it isn't the last word in your array
var phrase = 'this is my string';
var words = phrase.split(' ');
var result = '';
for (var i = 0; i < words.length; i++) {
var word = words[i];
result += word.substring(0, 3).toUpperCase();
if (i < words.length - 1) {
result += '_';
}
}
console.log(result);
"One-line" solution using String.replace(), String.toUpperCase() and String.slice() functions:
var string = "Hello there my friend",
replaced = string.replace(/\b(\w{1,3})(\w+\s?|\s)/g, '$1_').toUpperCase().slice(0,-1);
console.log(replaced);
console.log("Hello there my friend".split(" ").map((a)=>a.substring(0, 3)).join("_").toUpperCase());
I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>
I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));
I use this regex
str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);
butI not understood how can use variable as quantificator, that is how write this:
var number = 2;
var p = str.match(/\d{number}/);
P.S. I see this page JavaScript regex pattern concatenate with variable
but not understood how use example from these posts, in my case.
You need to build your regex as a string and pass it to the RegExp constructor:
var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);
Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex.
var number = "2"
var p = new RegExp("\\d{" + number + "}");
This should work:
var str = "asd34rgr888gfd98";
number = 3;
p = str.match(new RegExp('\\d{' + number + '}'));
alert(p[0]);
var str = "test's t\r and t\n";
str = str.replace(/'/g, "\'");
str = str.replace(/\r/g, "\\r");
str = str.replace(/\n/g,"\\n");
Is it possible to do these 3 replaces in single statement?
I want escape these particular chars. With out escaping it makes some problem. "\n" following chars goes to next line. While passing this as parameter it ll not get it as "\n" in the server.
Try this:
str.replace(/'|\r|\n/g, function($0) {
var trans = {"\r":"r", "\n":"n"};
return "\\" + (trans.hasOwnProperty($0) ? trans[$0] : $0);
})
You can also chain them:
var str = "test's t\r and t\n";
str = str.replace(/'/g, "\'").replace(/\r/g, "\\r").replace(/\n/g,"\\n");
var str = "test's t\r and t\n";
str = str.replace(/(\'|\r\n|\r|\n)/g, "\\");
alert("++++++++++++"+str+"++++++++++++");