Replace Multiple Strings With Multiple Other Strings

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

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]));

How to replace multiple substrings of a string?

Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'

Python: How to str.replace multiple different strings with the same replacement?

You can just use List-comprehension.

>>> [x.replace('!', '').replace('?','') for x in list_names]
['sdf', 'sdfds', 'afsafsa', 'afasf']

Also, if you have multiple strings to replace, you can even use regular expression combining them by | using re.sub function as mentioned below:

>>> import re
>>> [re.sub('\?|!', '', x) for x in list_names]
['sdf', 'sdfds', 'afsafsa', 'afasf']

How to replace multiple strings with possible overlap in JS?

Regular expressions seem like they would be your best bet for this.

I'm a bit of a novice still, but what you want can be achieved by running the replace() function in javascript on your string twice, each with a regular expression to match the users and hashtags respectively.

var tmpString = `@john and @johnathan went to see @sarah in their #hometown to look at her new #home.`;
console.log(tmpString);

tmpString = tmpString.replace(/(@(\w+))/gmi, `<a href="/user/$2">$1</a>`);
console.log(tmpString);
tmpString = tmpString.replace(/(#(\w+))/gmi, `<a href="/topic/$2">$1</a>`);
console.log(tmpString);

Replace multiple words in multiple strings

library(stringi)

stri_replace_all_regex(my_words, "\\b" %s+% my_replace$original %s+% "\\b", my_replace$replacement, vectorize_all = FALSE)

[1] "example R" "example R" "example R" "anthoer R" "now a C" "and another C" "example R tributary"

How to use str.replace to replace multiple pairs at once?

You can create a dictionary and pass it to the function replace() without needing to chain or name the function so many times.

replacers = {',':'','.':'','-':'','ltd':'limited'} #etc....
df1['CompanyA'] = df1['CompanyA'].replace(replacers)

Replace string with multiple strings

You could take a closure over the index and increment the index and adjust with the lenght of the array.

var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",    a = ["b", "c", "d"];    c = str.replace(/a/g, (i => () => a[i++ % a.length])(0));
console.log(c);

Replace multiple strings between two indexes with in strings

  1. Do not use a map if you do not need a
  2. No need to split unless you MUST use splice

Method using start and end - note I sort the roles so we start at the highest position

let str = "I want chicken pizza and cheese pizza from point restaurant";

let roles = [{
"start": 7,
"end": 14,
"typeId": "TYPE1",
"type": "toppings",
"text": "chicken"
},
{
"start": 25,
"end": 31,
"typeId": "TYPE1",
"type": "toppings",
"text": "cheese"
},
{
"start": 15,
"end": 20,
"typeId": "TYPE4",
"type": "main ingredient",
"text": "pizza"
}
];

let styledStr = str;
roles.sort((a,b)=>b.start-a.start)
roles.forEach(r => {
const { start, end, typeId, text } = r;
// Using substring because it is more readable and saves a split
styledStr = styledStr.substring(0,start) + typeId + styledStr.substring(end)
styledStr.slice(start,end,typeId)
});
console.log(styledStr)


Related Topics



Leave a reply



Submit