Split string into two parts [duplicate] - javascript

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, '');

Related

How to split string with multiple semi colons javascript

I have a string like below
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
I want to split above string with semi colon, so want the array like
var result = [ "Name:Sivakumar ; Tadisetti", "Country:India" ]
But as the name contains another semi colon, I am getting array like
var result = [ "Name:Sivakumar ", "Tadisetti", "Country:India" ]
Here Sivakumar ; Tadisetti value of the key Name
I just wrote the code like exampleString.split(';')... other than this not able to get an idea to proceed further to get my desired output. Any suggestions?
Logic to split: I want to split the string as array with key:value pairs
Since .split accepts regular expressions as well, you can use a one that matches semicolons that are only followed by alphanumeric characters that end in : (in effect if they are followed by another key)
/;(?=\w+:)/
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India";
var result = exampleString.split(/;(?=\w+:)/);
console.log(result)
here is an approach which we first split the input on ; and then concat the element without : with the previous one; since it shouldn't being spited.
let exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
let reverseSplited = exampleString.split(";").reverse();
let prevoiusString;
let regex = /[^:]+:.*/;
let result = reverseSplited.map( str => {
if(regex.test(str)) {
if(prevoiusString){
let returnValue = str + ";" + prevoiusString;
prevoiusString = null;
return returnValue
}
return str
}
prevoiusString = str;
}).filter(e=>e);
console.log(result);

How to replace multiple strings with other multiple strings at a time in javascript? [duplicate]

This question already has answers here:
Replace multiple strings with multiple other strings
(27 answers)
Closed 3 years ago.
I have a string prototype whose code is given below:
String.prototype.replaceAll = function(str1, str2, ignore) {
return this.replace(
new RegExp(
str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"
):str2
)};
Usage:
var a = "I am Javascript";
console.log(
a.replaceAll("am", "love")
); // => I love Javascript
But when it comes to multiple exchange of characters or words, I have to run the prototype multiple times to achieve it. But I have thought of something like this:
var a = "I am Java";
console.log(
a.replaceAll(["am" , "Java"], ["love", "Javascript"])
); // => I love Javascript
So can you help me to achieve it? Or there is any other alternative?
I'd prefer to store replacements as key-value pairs in an object or as an array of pairs. Regardless of the format, you can dynamically create a regex by joining the values you want to replace using | alternation. Then give replace a callback function and use its match parameter as a key to look up its corresponding pair in the swaps object.
const s = "I am Java";
const swaps = {am: "love", Java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "g");
console.log(s.replace(pattern, m => swaps[m]));
To handle case-insensitive replacements, ensure all keys in swaps are lowercase (either programmatically or manually, depending on usage) and lowercase the matches before keying in:
const s = "I am Java";
const swaps = {am: "love", java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "gi");
console.log(s.replace(pattern, m => swaps[m.toLowerCase()]));
This works.
String.prototype.replaceAll = function(str1, str2, ignore) {
let flags = 'g';
if (ignore) {
flags += 'i';
}
if (Array.isArray(str1) && Array.isArray(str2)) {
let newStr = this;
str1.map((element, index) => {
if (str2[index]) {
newStr = newStr.replace(new RegExp(element, flags), str2[index]);
}
return newStr;
});
return newStr;
}
else {
return this.replace(new RegExp(str1, flags), str2);
}
}

Why the output of this regex varies? [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 3 years ago.
I am trying to construct regex using RegExp() based on provided string. This string is provide by a request or generated dynamic.
I have two different inputs
1) "te\*" -> which expects to remove special behavior of '*'. Expected regex output should be /te\*/g.
2) "te*" -> Which uses the special behavior of 0 or More repeating character 'e'. Expected regex output should be /te*/g.
new RegExp("te\*") -> /te*/
new RegExp("te*") -> /te*/
My first question is why the result of both inputs end up is same? I guess it may be because of escaping. Then I tried
new RegExp("te\\*") -> /te\*/
I added escaping after looking in to the doc.
var escapeString = function (string){
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
Using escape function ended up same result than different one.
escapeString("te\*") -> /te\\*/
escapeString("te*") -> /te\\*/
I tried unescaping by replacing two blackslashes by none. I am not pretty sure whether this unescaping is correct.
var unescapeString = function(string){
return string.replace(/\\\\/g,"");
}
I was wondered why didn't the regex result changed. I couldn't figure out how should make difference of those inputs?
With this behavior, I decided to try with few things like escaping and do unescaping input works or not.
1) First Input "te\*"
var unescapeString = function(string){
return string.replace(/\\\\/g,"");
}
var escapeString = function (string){
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var aa = "te\*";
var a1_es = escapeString(aa);
aa_arr = [];
aa_arr.push(a1_es);
console.log("es1 => ", aa_arr);
var aa_es = escapeString(aa_arr[0]);
aa2_arr = [];
aa2_arr.push(aa_es);
console.log("es2 => ", aa2_arr);
var aa_ues = unescapeString(aa2_arr[0]);
aa_uesArr = [];
aa_uesArr.push(aa_ues);
console.log("ues ===>", aa_uesArr);
var rgex = new RegExp(aa_uesArr[0]);
console.log("rgex2 ===> ",rgex )
Output for above snippet:
es1 => [ 'te\\*' ]
es2 => [ 'te\\\\\\*' ]
ues ===> [ 'te\\*' ]
rgex2 ===> /te\*/
My expected output for First Input is fine.
2) Second input "te*"
var actual = "te*";
var unescapeString = function(string){
return string.replace(/\\\\/g,"");
}
var escapeString = function (string){
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var actual_es1 = escapeString(actual);
actual1_arr = [];
actual1_arr.push(actual_es1);
console.log("es1 => ", actual1_arr);
var actual_es = escapeString(actual1_arr[0]);
actual_arr = [];
actual_arr.push(actual_es);
console.log("es2 => ", actual_arr);
var actual_ues = unescapeString(actual_es);
actual_uesArr = [];
actual_uesArr.push(actual_ues);
console.log("ues ===>", actual_uesArr);
var actualrgex = new RegExp(actual_uesArr[0]);
console.log("actualrgex ===> ",actualrgex );
Output for above snippet
es1 => [ 'te\\*' ]
es2 => [ 'te\\\\\\*' ]
ues ===> [ 'te\\*' ]
actualrgex ===> /te\*/
Expected output for Second Input Varies. It should be /te*/.
I would like to know whether am i missing something here or heading towards different direction.
I appreciate any help or suggestions of alternative approach to resolve this. Thanks for reading this long post!!!
check out first what the strings are, before building the regex
so you notice how the \* becomes a single * long before getting into the regex
and that is because of the backslash \ behavior in JavaScript Strings
var arr = ['te\*', 'te*', 'te\\*'];
arr.forEach(function(s) {
console.log('s => ', s);
});
and just in case you wanna see it in action in your code snippet:
var escapeString = function (string){
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var arr = ['te\*', 'te*', 'te\\*'];
arr.forEach(function(s) {
console.log('s => ', s);
var es1 = escapeString(s);
console.log('es1 => ', es1);
console.log('regex1 ===> ', new RegExp(es1));
var es2 = escapeString(es1);
console.log('es2 => ', es2);
console.log('regex2 ===> ', new RegExp(es2));
});

Split sentence by space mixed up my index

I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution

regex to find specific strings in javascript

disclaimer - absolutely new to regexes....
I have a string like this:
subject=something||x-access-token=something
For this I need to extract two values. Subject and x-access-token.
As a starting point, I wanted to collect two strings: subject= and x-access-token=. For this here is what I did:
/[a-z,-]+=/g.exec(mystring)
It returns only one element subject=. I expected both of them. Where i am doing wrong?
The g modifier does not affect exec, because exec only returns the first match by specification. What you want is the match method:
mystring.match(/[a-z,-]+=/g)
No regex necessary. Write a tiny parser, it's easy.
function parseValues(str) {
var result = {};
str.split("||").forEach(function (item) {
var parts = item.split("=");
result[ parts[0] /* key */ ] = parts[1]; /* value */
});
return result;
}
usage
var obj = parseValues("subject=something||x-access-token=something-else");
// -> {subject: "something", x-access-token: "something-else"}
var subj = obj.subject;
// -> "something"
var token = obj["x-access-token"];
// -> "something-else"
Additional complications my arise when there is an escaping schema involved that allows you to have || inside a value, or when a value can contain an =.
You will hit these complications with regex approach as well, but with a parser-based approach they will be much easier to solve.
You have to execute exec twice to get 2 extracted strings.
According to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.
Usually, people extract all strings matching the pattern one by one with a while loop. Please execute following code in browser console to see how it works.
var regex = /[a-z,-]+=/g;
var string = "subject=something||x-access-token=something";
while(matched = regex.exec(string)) console.log(matched);
You can convert the string into a valid JSON string, then parse it to retrieve an object containing the expected data.
var str = 'subject=something||x-access-token=something';
var obj = JSON.parse('{"' + str.replace(/=/g, '":"').replace(/\|\|/g, '","') + '"}');
console.log(obj);
I don't think you need regexp here, just use the javascript builtin function "split".
var s = "subject=something1||x-access-token=something2";
var r = s.split('||'); // r now is an array: ["subject=something1", "x-access-token=something2"]
var i;
for(i=0; i<r.length; i++){
// for each array's item, split again
r[i] = r[i].split('=');
}
At the end you have a matrix like the following:
y x 0 1
0 subject something1
1 x-access-token something2
And you can access the elements using x and y:
"subject" == r[0][0]
"x-access-token" == r[1][0]
"something2" == r[1][1]
If you really want to do it with a pure regexp:
var input = 'subject=something1||x-access-token=something2'
var m = /subject=(.*)\|\|x-access-token=(.*)/.exec(input)
var subject = m[1]
var xAccessToken = m[2]
console.log(subject);
console.log(xAccessToken);
However, it would probably be cleaner to split it instead:
console.log('subject=something||x-access-token=something'
.split(/\|\|/)
.map(function(a) {
a = a.split(/=/);
return { key: a[0], val: a[1] }
}));

Categories

Resources