Javascript - String split [duplicate] - javascript

This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]

Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].

This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)

Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]

in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)

var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))

Related

change words at particular location in javascript string [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed last year.
var str = "Hello world";
str.charAt(2)="P"//instead of l i am assigning the value P
console.log(str)
I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string
You need to make an array out of the string to replace by index.
The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below
1 way can be to split the string using two substrings and stuff the character between them
var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
2 way can be to convert the string to character array, replace one array member and join it
var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)

String replace Double quotes into curly brackets [duplicate]

This question already has answers here:
Converting ″Straight Quotes″ to “Curly Quotes”
(7 answers)
Closed 4 years ago.
How to replace all the Double quotes into both open and close curly brackets.
let str = "This" is my "new" key "string";
I tried with this regex
str.replace(/"/,'{').replace(/"/,'}')
But I end up with this:
{This} is my "new" key "string"
Here am getting only the first word is changing but i would like to change all the words.
I want the result to be:
{This} is my {new} key {string}
Thanks in advance.
Try using a global regex and use capture groups:
let str = '"This" is my "new" key "string"';
str = str.replace(/"([^"]*)"/g, '{$1}');
console.log(str);
The "([^"]*)" regex captures a ", followed by 0 or more things that aren't another ", and a closing ". The replacement uses $1 as a reference for the things that were wrapped in quotes.
Your code currently is only working for the first occurrence of each { and }. The easiest way to fix this would be to loop while there is still a " in str:
let str = '"This" is my "new" key "string"';
while (str.includes('"')) {
str = str.replace(/"/,'{').replace(/"/,'}');
}
console.log(str);
Try like this
str.replace(/\"(.*?)\"/g, "{$1}")
we need to use g-gobal flag. Here capturing string between double quotes "", then replace with matched string curly braces
A very simple way to do that is to iterate over string as an array and every time it encounters character " replace it either by { or by } repeatedly.
let str = '"This" is my "new" key "string"';
let strArray = str.split("");
let open = true;
for (let i = 0; i < strArray.length; ++i) {
if (strArray[i] == '"') {
if (open === true) {
strArray[i] = '{';
}
else {
strArray[i] = '}';
}
open = (open == true) ? false : true;
}
}
str = strArray.join("");
console.log(str)

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

jQuery multiple replace [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/

JS split() function that ignores separator appearing inside quotation marks

Basically, like if you were to say
var string = 'he said "Hello World"';
var splitted = string.split(" ");
the splitted array would be:
'he' 'said' '"Hello World"'
basically treating the quotation mark'd portion as a separate item
So how would I do this in javascript? Would I have to have a for loop that goes over the string checking if the scanner is inside a set of quotation marks? Or is there a simpler way?
You could use regular expressions:
var splitted = string.match(/(".*?")|(\S+)/g);
Basically it searches at first for strings with any characters between quotes (including spaces), and then all the remaining words in the string.
For example
var string = '"This is" not a string "without" "quotes in it"';
string.match(/(".*?")|(\S+)/g);
Returns this to the console:
[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
First of all, I think you mean this:
var string = 'he said "Hello World"';
Now that we've got that out of the way, you were partially correct with your idea of a for loop. Here's how I would do it:
// initialize the variables we'll use here
var string = 'he said "Hello World"', splitted = [], quotedString = "", insideQuotes = false;
string = string.split("");
// loop through string in reverse and remove everything inside of quotes
for(var i = string.length; i >= 0; i--) {
// if this character is a quote, then we're inside a quoted section
if(string[i] == '"') {
insideQuotes = true;
}
// if we're inside quotes, add this character to the current quoted string and
// remove it from the total string
if(insideQuotes) {
if(string[i] == '"' && quotedString.length > 0) {
insideQuotes = false;
}
quotedString += string[i];
string.splice(i, 1);
}
// if we've just exited a quoted section, add the quoted string to the array of
// quoted strings and set it to empty again to search for more quoted sections
if(!insideQuotes && quotedString.length > 0) {
splitted.push(quotedString.split("").reverse().join(""));
quotedString = "";
}
}
// rejoin the string and split the remaining string (everything not in quotes) on spaces
string = string.join("");
var remainingSplit = string.split(" ");
// get rid of excess spaces
for(var i = 0; i<remainingSplit.length; i++) {
if(remainingSplit[i].length == " ") {
remainingSplit.splice(i, 1);
}
}
// finally, log our splitted string with everything inside quotes _not_ split
splitted = remainingSplit.concat(splitted);
console.log(splitted);​
I'm sure there are more efficient ways, but this produces an output exactly like what you specified. Here's a link to a working version of this in jsFiddle.

Categories