简体   繁体   English

用数组中的值替换字符串中的特定字符

[英]Replace specific characters in string with values from array

I'm building a web application and getting some descriptions from the server. 我正在构建一个Web应用程序,并从服务器获取一些描述。 Those strings that I'm getting sometimes include specific characters in them, which should be replaced with proper values. 我得到的那些字符串有时在其中包含特定的字符,应将其替换为适当的值。 An example of the string looks like this: 字符串的示例如下所示:

let str = 'Every next purchase provides you with additional %@ days 
of bonuses, up to %@ days.'

I need to replace '%@' with proper values. 我需要用适当的值替换'%@'。 Probably the best way to get those values is an array, since text may have one '%@' or more. 获取这些值的最佳方法可能是数组,因为文本可能具有一个'%@'或更多。 I've been thinking about dealing with this through substring method, but I'm not sure if that's the best way. 我一直在考虑通过子字符串方法处理此问题,但是我不确定这是否是最好的方法。

Example of values may be like [2,5]. 值的示例可能类似于[2,5]。 Then result should looks like: 'Every next purchase provides you with additional 2 days of bonuses, up to 5 days.' 然后结果应该是: 'Every next purchase provides you with additional 2 days of bonuses, up to 5 days.'

Thanks for any help. 谢谢你的帮助。

Use regex and replace method of string to replace character(s )in the string. 使用正则表达式和字符串的替换方法替换字符串中的字符。 It returns new string after the process. 在该过程之后,它将返回新的字符串。

let str = 'Every next purchase provides you with additional %@ days'; 
let regex = /%@/gi;
console.log(str.replace(regex, 'yourvalue'));

It depends how you replace it, you can use loop through and replace with array values with same value (not with unique one), again it depends on what you are trying to achieve. 这取决于您如何替换它,可以使用循环遍历并替换为具有相同值的数组值(而不是唯一值),这又取决于您要实现的目标。

 const str = 'Every next purchase provides you with additional %@ days %@'; const array = ['value1', 'value2']; const count = (str.match(/%@/gi) || []).length; const regex = /%@/; let newString; for (let i = 0; i < count; i++) { newString = i === 0 ? str.replace(regex, array[i]) : newString.replace(regex, array[i]); alert(newString); } 

Regarding substring() : The method extracts characters from string between two SPECIFIC indices. 关于substring() :该方法从两个SPECIFIC索引之间的字符串中提取字符。 Since you are getting data from the server, and I believe it's a dynamic data and the indexes of those characters can change, therefore using substring() might not help. 由于您是从服务器获取数据,并且我相信它是动态数据,并且这些字符的索引可以更改,因此使用substring()可能无济于事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM